AddWithValue adds no value
AddWithValue adds no value
When sending parameters from C# to SQL Server, instead of .AddWithValue()
:
string SomeString = "some string"; ... cmdObject.Parameters.AddWithValue("@StringParam", SomeString);
Most rightly suggest .Add()
instead (e.g. "Steve" in this Stack Overflow answer):
string SomeString = "some string"; ... cmdObject.Parameters.Add(new SqlParameter { ParameterName = "@StringParam", Value = SomeString, SqlDbType = SqlDbType.VarChar, Size = 255 // given the column is varchar(255) (-1 for max) });
Why? It allows you to be more explicit about the type being passed in, as well as the length, and has other performance benefits as well.
- Bob Beauchemin talks about multiple ways AddWithValue hurts performance:
Under the Table – How Data Access Code Affects Database Performance - Erik Darling explains the impact of parameter sizes in this answer:
Parameterized query creating many plans - Dan Guzman also talks about the performance issues:
AddWithValue is Evil - And Joel Coehoorn has been begging us all to stop using this method for years:
Can we stop using AddWithValue() already?
By: Aaron Bertrand
I am a passionate technologist with industry experience dating back to Classic ASP and SQL Server 6.5. I am a long-time Microsoft MVP, write at Simple Talk, SQLPerformance, and MSSQLTips, and have had the honor of speaking at more conferences than I can remember. In non-tech life, I am a husband, a father of two, a huge hockey and football fan, and my pronouns are he/him.