如何在SQL中使AND条件可选

时间:2017-01-31 11:18:45

标签: sql-server sql-server-2008 sql-server-2008-r2

    usp_demo_sp '2016-04-01',@EmpIDs
    usp_demo_sp '2016-04-01','111,222,333'

Query:
        select * from tbl_bill a, temp b
        where a.emplid=b.emplid
        and a.emplid in (select * from dbo.SplitString(REPLACE(replace(@EmpIDs,CHAR(13)+CHAR(10),'' ),CHAR(9),''), ','))

在上面的存储过程中,我使用上面的查询。 @empids参数是逗号分隔值。 此查询适用于单个或多个empid。 但是我需要实现条件,当@EmpIDs为null或''时,我需要删除以下条件

 and a.emplid in (select * from dbo.SplitString(REPLACE(replace(@EmpIDs,CHAR(13)+CHAR(10),'' ),CHAR(9),''), ','))

来自上面的查询。 请提出建议。

2 个答案:

答案 0 :(得分:2)

试试这个:

select * 
from tbl_bill a
join temp b
    on a.emplid=b.emplid
where ltrim(rtrim(isnull(@EmpIDs, ''))) = '' 
OR a.emplid in (
    select * 
    from dbo.SplitString(REPLACE(replace(@EmpIDs,CHAR(13)+CHAR(10),'' ),CHAR(9),''), ',')
)

请注意,我已将隐式联接更改为显式联接。

答案 1 :(得分:0)

Creating item foo
  Inside item foo
  Block is here. Executing it in item foo
  Creating item bar
    Inside item bar
    Block is here. Executing it in item bar
    Creating item biz
      Inside item biz
    Inside item bar! Adding item biz to []
    Creating item boz
      Inside item boz
    Inside item bar! Adding item boz to [biz []]
  Inside item foo! Adding item bar to []
  Creating item baz
    Inside item baz
  Inside item foo! Adding item baz to [bar [biz [], boz []]]