C# 如何在参数化查询中检查T-SQL中的值是否为null?

C# 如何在参数化查询中检查T-SQL中的值是否为null?,c#,sql-server,tsql,sql-server-2008,syntax,C#,Sql Server,Tsql,Sql Server 2008,Syntax,假设有一个表Product,其中包含ProductId(smallint)、Title(可空的nvarchar(100))和Price(money)列。标题可以是null 有一个查询必须返回与特定标题和特定价格匹配的产品: using (SqlCommand getProducts = new SqlCommand("select ProductId from Product where Title = @title and Price = @price", sqlConnection)) {

假设有一个表
Product
,其中包含
ProductId
(smallint)、
Title
(可空的nvarchar(100))和
Price
(money)列。标题可以是
null

有一个查询必须返回与特定标题和特定价格匹配的产品:

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);
}
对于SQL Server,在执行以下代码时,
title
设置为null(或可能也设置为空字符串),比较结果如下:

[...] where Title = NULL and Price = 123
由于正确的语法为:

[...] where Title is NULL and Price = 123
我可以根据标题的空检查更改查询字符串,但它将无法维护

Title
为null时,是否有一种干净的方法可以使比较工作而不使查询字符串不同?

您可以像这样使用IsNull()

using (SqlCommand getProducts = new SqlCommand("select ProductId from Product where IsNull(Title, '') = IsNull(@title, '') and Price = @price", sqlConnection))
如果标题为null,则比较将使用空字符串,而不是null

[编辑]在下面a1ex07的评论后更新。

您可以像这样使用IsNull()

using (SqlCommand getProducts = new SqlCommand("select ProductId from Product where IsNull(Title, '') = IsNull(@title, '') and Price = @price", sqlConnection))
[...] WHERE COALESCE(Title,'') = COALESCE(@Title,'') AND Price = 123
如果标题为null,则比较将使用空字符串,而不是null


[编辑]在下面a1ex07的评论后更新。

如果
@title
为空,那么对于
title
为空的
''=null
?如果
@title
为空,则
的结果为空(title.)=@title
也为空(false)。如果您再添加一个
ISNULL
ISNULL(Title,)=ISNULL(@Title,)
。在
@Title
为null的情况下,
@Title
的结果是否仍然会转换为
Title
为null的
@Title
为null=@title也为空(false)。如果您再添加1个
ISNULL
ISNULL(Title',)=ISNULL(@Title',)
,它可能会起作用。
[...] WHERE COALESCE(Title,'') = COALESCE(@Title,'') AND Price = 123