检查列表是否为空或为null然后检查SQL

时间:2016-03-15 08:48:42

标签: sql-server sql-server-2012

我有这样的查询,

with t as (
      <your query here>
     )
select t.id, t.name, t.randomid, trand.name as randomname
from t left join
     t trand
     on t.randomid = trand.id
where t.id in (select item from dbo.ufnSplit(@ids,','));

Here is code for ufnSplit

如何添加检查以便@ids为空或仅为空时使用where条件,仅当@ids不为空或空时我才想要这个条件?

where t.id in (select item from dbo.ufnSplit(@ids,','));

3 个答案:

答案 0 :(得分:2)

这将检查@ids是否为空或空,然后检查where子句。

with t as (
      <your query here>
     )
select t.id, t.name, t.randomid, trand.name as randomname
from t left join
     t trand
     on t.randomid = trand.id
where @ids = '' 
   or @ids is null
   or t.id in (select item from dbo.ufnSplit(@ids,','))

答案 1 :(得分:1)

试试这个where t.id in (select item from dbo.ufnSplit(@ids,',')) or nullif(@ids,'') is null; 子句

{{1}}

答案 2 :(得分:1)

您可以像这样使用条件WHERE子句:

with t as (
      <your query here>
     )
select t.id, t.name, t.randomid, trand.name as randomname
from t left join
     t trand
     on t.randomid = trand.id
where @ids IS NULL OR t.id IN (select item from dbo.ufnSplit(@ids,','));

因此,如果它NULL它将返回所有内容,否则它将评估OR子句的WHERE部分。

您可能需要编辑功能:dbo.ufnSplit以便正常处理NULL输入,以使其正常工作。