Consider the following code:
Dim sql = "SELECT * FROM MyTable WHERE value1 = @Param1"
If someCondition Then
sql = sql + " AND value2 = @Param2"
End If
Dim cmd As New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("@Param1", param1Value)
cmd.Parameters.AddWithValue("@Param2", param2Value)
Assuming that I built a complex sql statement dynamically that may or may not have included the @Param2
parameter - is there any harm in adding it to the command as a parameter?
My real use-case is obviously far more complicated than this, but in general, is this a pattern I should avoid; and if so, why?
The only point I would take note is the fact that if you call .AddWithValue
, you leave it up to SQL Server to figure out what the data type of the parameter will be.
SQL Server does a remarkably good job of guessing - but sometimes, it gets it "sub-optimally" and it would be helpful for you to provide the details.
So I personally tend to always use this snippet of code:
SqlParameter aParam = new SqlParameter("@Param1", SqlDbType.VarChar, 50);
aParam.Value = param1Value;
This has two main benefits:
You could easily wrap this in a e.g. static helper class, or even use it as an extension method.
It's a tad more work, but you get more control, and might avoid unnecessary, time-consuming datatype conversions and other unexpected side effects if you leave it up to SQL Server to guess your types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With