c# - Add more parameters then are used in the query? -
Is there a way to add a parameter to my SQL command in the way the engine will not complain if it did not use it in me Has been the question?
I have about 50 parameters to include in my query, but the need to include those parameters is highly dependent on the situation. I could easily remove 200 lines if I could just keep them above all and add my parameters and create my query.
A very simple / dumb / incorrect .. Example (yes, the solution here is to add the ID to the second block)
cmd.Parameters.Add (" @ Id ", SqlDbType.Int) .Value = id; Cmd.Parameters.Add ("@Name", SqlDbType.nVarChar, 250) .Value = name; If (id == null) cmd.CommandText = "Include tab (name) values (@ name)"; Else cmd.CommandText = "Update Tab SET name = @name WHERE id = @id";
returns this error:
System.Data.SqlClient.SqlException: parameterized query '(@ id, @ name)' parameter is expected ' @id ', which was not supplied
If this is not possible, then a simple' no 'will be enough to accept as a reply.
Is there a way to add a parameter to my SQL command in my query, just like Will the engine not complain? / P> If you add a parameter and do not use it, then ADO.NET does not complain. The error message you reported is because you are trying to use a parameter that you did not add-ons are most likely, Alternatively, tools like "Dapper" make it easy:
id
null
. Parameters containing values of null
not added - You DBNull.Value
:
cmd .Parameters.Add ("@ id", SqlDbType.Int). Value = ((object)) ?? DBNull.Value; Cmd.Parameters.Add ("@Name", SqlDbType.nVarChar, 250). Value = ((object) name) ?? DBNull.Value;
conn.Execute (sql, new {id, name}); // worked
Comments
Post a Comment