SharpDeveloper
Annoying Nulls in SQLParameters
If you read Creating SqlParameters Best Practices you will find the fun you have if you have null values:
SqlParameter[] sqlParams = new SqlParameter[] {
new SqlParameter("@Required", required),
questionCode == null ? new SqlParameter("@Code", DBNull.Value) : new SqlParameter("@Code", questionCode)
};
Here is a nice helper function to deal with nulls without having to manually check every time.
/// <summary>
/// Return a SqlParameter with DBNull value or value
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public static SqlParameter NullWrapper(string key, object value)
{
if (value == null)
return new SqlParameter(key, DBNull.Value);
else
return new SqlParameter(key, value);
}
Then you can use it as follows
SqlParameter[] sqlParams = new SqlParameter[] {
new SqlParameter("@UserID", userId),
new SqlParameter("@itemNo", itemNo),
General.NullWrapper("@expiryDate", expiryDate) //no need to check if null any more
};
Related Reading:
Other Interesting Posts
4 Responses to Annoying Nulls in SQLParameters
Leave a Reply Cancel reply
-
Articles
- January 2011
- April 2010
- March 2010
- February 2010
- January 2010
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- February 2009
- December 2008
- November 2008
- October 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
- June 2007
- May 2007
-
Meta








Its more easy do:
parameter??DBNull.Value
I dont quite understand.. can you be more explicit?
Rather than hack the parameter creation code, you might want to consider putting a default value of null in the relevant stored procedure parameter, then passing null (not DBNull) as the parameter. The data code will be interpreted as the parameter being missing, which will then be covered by the default value in the procedure…
You are right, if you can modify the source code of the stored proc, that is a good option too.