Annoying Nulls in SQLParameters

August 7th, 2009 by Sameer | Filed under Uncategorized.

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
            };

Other Interesting Posts

2 Responses to “Annoying Nulls in SQLParameters”

  1. Felipe Fujiy says:

    Its more easy do:

    parameter??DBNull.Value

  2. I dont quite understand.. can you be more explicit?

Leave a Reply