从T-SQL参数列表中获取不同的值

时间:2016-04-14 09:28:12

标签: sql sql-server-2008 tsql

我正在使用工具来生成SQL查询,我需要使用多个参数过滤其中一个查询。

查询类似于:

Select * 
From Products
Where (@ProductTypeIds is null or Product.ProductTypeId in (@ProductTypeIds))

我知道上面的查询在传统的SQL上是不正确的,请继续阅读..

基本上,我正在尝试应用过滤器,如果没有为@ProductTypeIds参数传递任何内容,则不应用where条件。

但是,当传递多个参数时,工具会将@ProductTypeIds转换为以下查询:

Select * 
From Products
Where (@ProductTypeIds1, @ProductTypeIds2  is null or Product.ProductTypeId in (@ProductTypeIds1, @ProductTypeIds2))

这显然是无效的查询。所以我认为我可以聪明并使用COALESCE检查它们是否为空:

Select * 
From Products
Where (COALESCE(@ProductTypeIds, null) is null or Product.ProductTypeId in (@ProductTypeIds))

正在正确翻译此查询,但是,现在我使用COALESCE会引发错误:

  

COALESCE的至少一个参数必须是一个不是NULL常量的表达式。

如何有效地检查@ProductTypeIds(被翻译成@ProductTypeIds1, @ProductTypeIds2的所有内容都为空,以便我可以应用过滤器或忽略?

换句话说,有没有办法Distinct参数列表来检查最终结果是null

由于

1 个答案:

答案 0 :(得分:2)

我不知道你的工具是如何工作的,但请尝试以下方法。

而不是检查null检查您的参数中永远不会出现的值,如:

WHERE COALESCE(@ProductTypeIds1, @ProductTypeIds2, -666) == -666 OR ...