让我们想象有一个表Product
与列ProductId
(smallint),Title
(可nvarlable nvarchar(100))和Price
(货币)。标题可以是是null
。如何在参数化查询中检查T-SQL中的值是否为空?
有它必须返回和产品匹配到一个特定的标题和具体价格查询:
using (SqlCommand getProducts = new SqlCommand("select ProductId from Product where Title = @title and Price = @price", sqlConnection))
{
getProducts.Parameters.AddWithValue("@title", title);
getProducts.Parameters.AddWithValue("@price", price);
}
当title
集执行以下代码为空(或者也可能为空字符串),用于SQL Server中,比较将是:
[...] where Title = NULL and Price = 123
它会返回一个空集,因为正确的语法是:
[...] where Title is NULL and Price = 123
我可以根据标题的空检查更改查询字符串,但它将不可维护。
当Title
为空时,是否有一种干净的方式可以在不使查询字符串不同的情况下进行比较工作?
在`@ title`为null的情况下,如果`Title`s为null,那么是不是仍然会转换为`''= NULL`? – 2011-02-10 17:00:51