36

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?

2

4 Answers 4

29

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.

1
  • 2
    Please be advised that there's an overload on .Add that let's you add a SqlParameter/OleDbParameter/DbParameter. When you omit the parameter name (by setting it to NULL) in the parameter instance you'll get a nasty performance hit: the .Net framework will create names for you 'Parameter1..x'. Now this seems silly for a SqlParameter, you would want to match the @variable. With OleDbParameter however... Feb 2, 2017 at 14:42
12

I believe there are also some cons to using AddWithValue which affect the SQL Cache Excection Plan, see the Parameter Length section here

2
  • 1
    Considering this horrifying sentence in the linked article: "By not specifying the length when you're using ParameterCollection.AddWithValue, you can have as many different queries in the plan cache as you have different string lengths." this may be most valuable response here :) Mar 4, 2015 at 19:46
  • that article is pretty old, is that still the behavior?
    – Maslow
    Sep 17, 2015 at 12:59
3

Using AddWithValue() adds parameter with length of current value. If the length of your parameter value varies often this means new plan is generated every time. This makes your queries run slower(additional time for parsing, compiling) and also causes higher server load.

2

I'd use the AddWithValue for normal cases. And use Add(name, dbtype... only when your column type is different from how .net converts the CLR type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.