2016-03-15 61 views
1

我有这样的查询,检查列表为空或则空检查SQL

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不为null或空时,我才需要这个条件?

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

回答

1

这将检查@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

试试这个Where条款

where t.id in (select item from dbo.ufnSplit(@ids,',')) or nullif(@ids,'') is null; 
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输入以使其正常工作。