When should I use Parameters. Add/AddWithValue
? In the following MSDN example they use Parameters.Add
for int
and Parameters.AddWithValue
for string
command.Parameters.Add("@ID", SqlDbType.Int); command.Parameters["@ID"].Value = customerID; command.Parameters.AddWithValue("@demographics", demoXml);
What is the best to use for datetime
AddWithValue replaces the SqlParameterCollection. Add method that takes a String and an Object. The overload of Add that takes a string and an object was deprecated because of possible ambiguity with the SqlParameterCollection.
Add overload that takes a String and a SqlDbType enumeration value where passing an integer with the string could be interpreted as being either the parameter value or the corresponding SqlDbType value. Use AddWithValue whenever you want to add a parameter by specifying its name and value.
Use Add
if you want to make all explicit with a little bit more work. Use AddWithValue
if you are lazy. AddWithValue
will derive the type of the parameter of its value, so ensure that it's the correct type. You should, for example, parse a string
to int
if that is the correct type.
There is one reason to avoid Add
: if your parameter type is int
you must be careful with the overload that takes the parameter-name and an object since then another overload is chosen with the SqlDbType
-enum.
From remarks (method overload is even obsolete
now):
Use caution when you are using this overload of the
SqlParameterCollection.Add
method to specify integer parameter values. Because this overload takes a value of type Object, you must convert the integral value to an Object type when the value is zero ... If you do not perform this conversion, the compiler assumes that you are trying to call theSqlParameterCollection.Add(string, SqlDbType)
overload.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With