7

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue.aspx

I'm used to adding sql parameters to a sqlCommand using the add() function. This allows me to specify the type of the sqlParameter, but it requires another line to set the value.

It's nice to use the AddWithValue function, but it skips the "specify the parameter type" step.

I'm guessing this causes the parameters to be sent over as strings contained within single quotes (''), but I'm not sure.

Is this the case, and does this cause significantly slower performance of the stored procedures?

Note: I understand that it is nice to validate user data on the .NET side of things by specifying the data type for params -- I'm only concerned about reflection-type overhead of AddWithValue either on the .NET or SQL side.

2 Answers 2

6

The type deduction happens client-side. Inside SqlParameter, it basically has a bit switch statement to determine what SQL type the value you specify corresponds to. So there's no difference in what is sent to SQL Server, but there is a very small overhead to determine what SQL type your .NET type corresponds to. In the grand scheme of things, the performance cost wouldn't even show up as a blip next to the time spent actually in the database call.

You can still do it in one line while specifying the SQL type:

cmd.Parameters.Add("@something", SqlDbType.NVarChar).Value = someString;
1
  • I was about to do an extension method, but this looks much better.
    – Fat Shogun
    Dec 14, 2015 at 16:28
0

Dean's method works perfectly well, but I think it looks a little odd. Here's an extension method that you can use to overload AddWithValue to take in a SqlDbType so that you can turn the function call into a one liner:

<Extension()>
Public Function AddWithValue(ByVal sqlParameterCollection As SqlParameterCollection,
                             ByVal parameterName As String,
                             ByVal value As Object,
                             ByVal sqlDbType As SqlDbType) As SqlParameter
    sqlParameterCollection.Add(parameterName, sqlDbType)
    sqlParameterCollection(parameterName).Value = value
    Return sqlParameterCollection(parameterName)
End Function

Then call it like this:

cmd.Parameters.AddWithValue("@entity_uid", clientId, SqlDbType.Int)

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.