我有5个文本框:
< TextBox Name =“txbFirstName”/>< TextBox Name =“txbLastName”/>< TextBox Name =“txbCity”/>< TextBox Name =“txbAddress”/>< TextBox Name =“txbPhone”…
你可以为AddWithValue()创建一个扩展方法,并在实际值为NULL时传递一个额外的第三个参数作为你想要的值
public static class SqlParameterCollectionExtensions { public static SqlParameter AddWithValue(this SqlParameterCollection target, string parameterName, object value, object nullValue) { if (value == null) { return target.AddWithValue(parameterName, nullValue); } return target.AddWithValue(parameterName, value); } }
后来这样称呼它
database.sqlCommand.Parameters.AddWithValue("@City", txbCity.Text, "IS NULL");
参数的值对应于a NULL SQL Server数据库中的值是 DBNull.Value 。
NULL
DBNull.Value
Parameters.Add(锟斤拷@NAME锟斤拷, SqlDbType.<type>).Value = argument == null ? DBNull.Value : argument;
基本上:没有。
除非您已禁用ANSI NULL语法(请不要这样做),否则您需要 不同的SQL 测试 NULL 。一个常见的技巧(易于编写,但效率不高)是欺骗:
WHERE (FirstName = @FirstName OR (@FirstName IS NULL AND FirstName IS NULL)) AND (LastName = @LastName OR (@LastName IS NULL AND LastName IS NULL)) -- etc x5
(或者你想为空值执行的任何测试) - 并使用类似的东西:
database.sqlCommand.Parameters.AddWithValue("@FirstName", txbFirstName.Text.DBNullIfEmpty()); database.sqlCommand.Parameters.AddWithValue("@LastName", txbLastName.Text.DBNullIfEmpty()); // etc x5
哪里 DBNullIfEmpty 看起来像是这样的:
DBNullIfEmpty
internal static class MyExtensionMethods { public static object DBNullIfEmpty(this string value) { if(string.IsNullOrWhiteSpace(value)) return DBNull.Value; return value; } }