37

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

30

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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...
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 Comments

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 :)
that article is pretty old, is that still the behavior?
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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.