Link to home
Start Free TrialLog in
Avatar of kishore_peddi
kishore_peddi

asked on

Difference between "Add" and "AddWithValue" for command parameters ...

Hi,

I have the following info:

SqlCommand cmd = new SqlCommand("StoredProcedureName", cn);
cmd.Parameters.AddWithValue("@typ", dt);

What is the difference between "Add" and "AddWithValue" ? Means:

cmd.Parameters.Add(.....)
cmd.Parameters.AddWithValue(.....)

And when to use what ? Can you please explain me in simple terms with simple examples ?

Thanks
Avatar of Göran Andersson
Göran Andersson
Flag of Sweden image

cmd.Parameters.AddWithValue("@typ", dt);
is equivalent to:
cmd.Parameters.Add("@typ", dt);

The later one is deprecated in favor of the first, as it is clearer.

Specify the data type of the parameter if you know it. Example:

cmd.Parameters.Add("@typ", SqlDbType.Int).Value = td;
SOLUTION
Avatar of SQL_SERVER_DBA
SQL_SERVER_DBA
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of kishore_peddi
kishore_peddi

ASKER

Can you please make this simple to understand with a small example ? I want to understand the basics behind the scenes.

AddWithValue replaces the SqlParameterCollection.Add method that takes a String and a 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.

For SqlDbTypeXml enumeration values, you can use a string, an XML value, an XmlReader derived type instance, or a SqlXml object.

Appreciate your time, patience and help !!

Thanks
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial