tags:

views:

54

answers:

1

I have 2 samples that effectively do the same thing -- Sample 1:

command.Parameters.Add(ParamFoo, SqlDbType.Int)
command.Parameters(ParamFoo).Value = fooVal

Sample 2:

command.Parameters.AddWithValue(ParamBar, barVal)

Which sample would be recommended? I know that the second sample is making some conversions. Wouldn't it be best to not require conversions and go with the first sample?

+5  A: 

As you posted your code, is completely irrelevant. Both variants will perform identically, there will be no way you can measure the cost of in-client converts against the huge background of the database call.

However, there is a very very big known problem when barVal is of type String. The SqlClient will add the parameters as type NVARCHAR and when used in SQL expressions in comparing with a VARCHAR column, the SQL type precedence rules will require the column to be converted to NVARCHAR instead of the variable to be converted to VARCHAR, and this changes index seeks into table scans and has disastrous performance consequences.

Remus Rusanu
+1 for the warning and explanation about the implications of the type precedence rules on (N)VARCHAR
Lucero
+1: Appreciate the warning. Duly noted.
dboarman
I guess, if I am reading this correctly, for `String` data types, I should opt for the two-line sample (#1).
dboarman
For strings, if tthe parameter is compared with varchar columns (as in `SELECT ... FROM .... WHERE name=@name` where `name` id varchar) you should absolutely make sure that the parameter is added as SqlDbType.Varchar, or modify the command text to force force the comparison as varchar: `SELECT ... FROM ... WHERE name=cast(@name as varchar(...))`
Remus Rusanu
Excellent. I'll definitely take care of this.
dboarman