I have a series of inserts to be made on a table with a very large number of columns, e.g.:
INSERT INTO Table1 (A,B,C,...,Z) VALUES (@a,@b,@c,...,@z)
All the fields (A through Z) are nullable. You cannot perform the insert if you fail to explicitly set a command parameter that’s been written in the command text.
Since the column names are not really sequential (all have pretty random names), is there an easy way to loop through the parameters in the command text and set them to DBNull.Value? Or do I manually have to write out:
cmd.Parameters.AddWithValue("@a", DBNull.Value);
cmd.Parameters.AddWithValue("@b", DBNull.Value);
cmd.Parameters.AddWithValue("@c", DBNull.Value);
...
cmd.Parameters.AddWithValue("@z", DBNull.Value);
Or is the proper solution to build which columns are actually in-use and concatenate them together (and used parameters), then set the used parameters?
I tend to shy away from concatenation solutions for queries to avoid potential injection attacks.
Here’s a more concise/cleaner way to set each parameter to null:
I would also tend to shy away from the concatenation solution, but that might be different if your columns have default values defined in the DB, which would(?) be overwritten if you explicitly set them null in your
insertstatement.