SqlParameters and NULL values
This is just a tip about using SqlCommand objects with SqlParameters and null database values. Here’s one way to add a parameter to a command object:
SqlParameter param = sqlCmd.Parameters.Add(”@FirstName”, SqlDbType.VarChar);
param.Value = ‘ben’;
This adds a parameter named ‘FirstName’ with a datatype of ‘VarChar’ and a value of ‘ben’ to my SqlCommand. Now, if you wanted to make the value of the parameter a null value, this is what I typically do:
SqlParameter param = sqlCmd.Parameters.Add(“@FirstName”, SqlDbType.VarChar);
param.Value = null;
Since the Value property of a parameter is of type System.Object, you can simply set it to null. This is wrong. Don’t do it. You’ll get exceptions about missing parameters. I ALWAYS forget this and I’m ALWAYS confused by the errors until I remember this. If you set the parameter value to null, the SqlCommand must simply exclude the parameter when it executes, which would cause the missing parameter error. Instead, this is how you set the value of a parameter to null:
SqlParameter param = sqlCmd.Parameters.Add(“@FirstName”, SqlDbType.VarChar);
param.IsNullable = true;
param.Value = System.DBNull.Value;
There is a special class ‘DBNull’ that is used to represent NULL values, so if you do it like the example above, you should be all set.
ewise said,
Wrote on January 5, 2006 @ 3:07 pm
See, now you don’t run into this in VB because there is no “null”. Nothing is the VB equivalent so the whole DBNull.Value thing is a bit easier to catch.
Let the language wars begin!
Anonymous said,
Wrote on January 5, 2006 @ 4:34 pm
does it go null if you simply don’t set the value?
breichelt said,
Wrote on January 5, 2006 @ 5:01 pm
Eric, I bet I would still manage to goof it
Wheneve I have to code in VB, my mind always translates Nothing to null, so I bet I would still try it.
Eber, thats a great question, so I fired up Reflector and looked at the SqlParameter constructor. The value of the SqlParameter class gets initialized to null, not DBNull.Value, which is what we want. I took a screenshot of reflector so you can take a look.
http://codebetter.com/photos/ben.reichelt/images/136294/original.aspx