Basically Commands
has Parameters
and parameters has functions like Add
, AddWithValue
, and etc. In all tutorials i've seen, i usually noticed that they are using Add
instead of AddWithValue
.
.Parameters.Add("@ID", SqlDbType.Int)
vs
.Parameters.AddWithValue("@ID", 1)
Is there a reason NOT to use AddWithValue
? I'd prefer to use that over
Parameters.Add("@ID", SqlDbType.Int, 4).Value = 1
since it saves my coding time. So which is better to use? Which is safe to use? Does it improves performance?
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.
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.
With Add()
method you may restrict user input by specifying type and length of data - especially for varchar
columns.
.Parameters.Add("@name",SqlDbType.VarChar,30).Value=varName;
In case of AddWithValue() (implicit conversion of value) method, it sends nvarchar value to the database.
I believe there are also some cons to using AddWithValue which affect the SQL Cache Excection Plan, see the Parameter Length section here
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