2011-02-10 114 views
0

让我们想象有一个表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为空时,是否有一种干净的方式可以在不使查询字符串不同的情况下进行比较工作?

回答

2
[...] WHERE COALESCE(Title,'') = COALESCE(@Title,'') AND Price = 123 
1

您可以使用ISNULL()这样的...

using (SqlCommand getProducts = new SqlCommand("select ProductId from Product where IsNull(Title, '') = IsNull(@title, '') and Price = @price", sqlConnection)) 

如果标题为空,则空字符串将被用于比较,而不是空。

更新后a1ex07的评论如下。

+0

在`@ title`为null的情况下,如果`Title`s为null,那么是不是仍然会转换为`''= NULL`? – 2011-02-10 17:00:51

相关问题