Is there a way to add a parameter to my SqlCommand in a way that the engine will not complain if it's not used in my query?
I have about 50 parameters to include in my query but which parameters need to be included depends highly on the situation. I could easily delete 200 lines of code if i could just put them all on top and build my query after adding my params.
A very simple / dumb / wrong.. example (yes, the solution here is to add id to the else clause)
cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
cmd.Parameters.Add("@name", SqlDbType.nVarChar, 250).Value = name;
if(id == null) cmd.CommandText = "INSERT INTO tab (name) VALUES (@name)";
else cmd.CommandText = "UPDATE tab SET name = @name WHERE id = @id";
This returns the error:
System.Data.SqlClient.SqlException: The parameterized query '(@id,@name) ' expects the parameter '@id', which was not supplied
If it's not possible, a simple 'No' will suffice to be accepted as an answer..