SqlCommand.Parameters.Add() vs SqlCommand.CreateParameter()

When doing some quick research on SQL Parameters with SqlCommand, I noticed two methods which seemed to perform the same task, SqlCommand.Parameters.Add() and SqlCommand.CreateParameter().  After looking into each method on MSDN, I noticed that CreateParameter() will simply create the parameter, while Parameters.Add() will create the parameter and add it to the parameter collection.

SqlCommand.Parameters.Add()

The following example will create a SQL command object, create and add to the parameter list in one step, then add and assign values to the parameters.

SqlCommand command = new SqlCommand(someCommandText,someConnection)
command.Parameters.Add("@ID", SqlDbType.Int);
command.Parameters["@ID"].Value = customerID;

SqlCommand.CreateParameter()

The following will create a sql command object, add and assign values, then add to the parameter list. A few more steps than the previously mentioned Parameters.Add()

SqlCommand command = new SqlCommand(someCommandText,someConnection)
SqlParameter sqlParam = command.CreateParameter();
sqlParam.SqlType = SqlType.Int;
sqlParam.Value = 5;
sqlParam.ParameterName = "ID";
command.Parameters.Add(sqlParam);

Jacob Saylor

Software developer in Kentucky

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: