Excerpt from: http://www.cnblogs.com/ccweb/p/3403492.html
using (SqlCommand cmd =NewSqlCommand ()) {cmd. Connection =New SqlConnection (@"Data source=pc201305032338\sqlexpress;initial catalog=dbtest;integrated Security=true);; Cmd. Connection.Open (); Cmd. CommandType = CommandType.StoredProcedure; cmd. CommandText = "checkdbnull "; SqlParameter p1 = new SqlParameter (); P1. ParameterName = " @p1 " Span style= "color: #000000;" >; P1. DbType = dbtype.string; P1. Value = nullstring rslt = cmd. ExecuteScalar (). ToString (); }
Running the above code will throw " procedure or function ' Checkdbnull ' requires parameter ' @p1 ', but this parameter is not provided. ", the problem is in P1. Value = null This sentence, this null may be an object's property, but as long as null will throw the above exception.
Reason
. NET Framework rules: Idataparameter When sending a null parameter value to the server, the user must specify DBNullinstead of NULL. A null value in the system is an empty object with no value. The DBNull is used to represent a null value.
Solution
When assigning a value to SqlParameter, if the parameter value is NULL, the parameter is assigned a value of DBNull.Value, such as: P1.value = DBNull.Value
Reference
Idataparameter interface, the SqlParameter class implements the interface: public sealed class Sqlparameter:dbparameter, IDbDataParameter, Idataparameter, ICloneable
The difference between DBNull and NULL is that NULL is an invalid object reference in. Net; DBNull is a class, DBNull.Value is its only instance, which refers to the value in. NET when the data in the database is empty (<NULL>).
Sqlparameter.value = NULL Thrown by database exception