如何避免在sqlserver中声明的变量中出现空条件

时间:2018-09-19 08:46:21

标签: sql-server tsql sql-server-2016

CREATE TABLE #UserCompany
    ([ID] int, [CustId] varchar(2), [CustName] varchar(1), [Status] int)
;

INSERT INTO #UserCompany
    ([ID], [CustId], [CustName], [Status])
VALUES
    (1, 'a1', 'A', null),
    (2, 'a1', 'A', null),
    (3, 'a2', 'B', null),
    (4, 'a3', 'B', null),
    (5, 'a4', 'C', null),
    (6, 'a4', 'C', null),
    (7, 'a4', 'D', null),
    (8, 'a6', 'E', null)
;select * from #UserCompany

在传递一些价值的同时,获取价值

declare @id varchar(100)='1,2'
select * from #UserCompany where id in (select  CAST(value AS int)  FROM string_SPLIT(@id, ','))

如果iam传递null,即使我们不传递任何如下所示的信息,iam也无法获取任何值

declare @id varchar(100)=null
select * from #UserCompany where id in (select  CAST(value AS int)  FROM string_SPLIT(@id, ','))

输出应为总计表应显示

1 个答案:

答案 0 :(得分:3)

declare @id varchar(100)='1,2'

select * 
from #UserCompany 
where id in (select  CAST(value AS int)  FROM string_SPLIT(@id, ','))
   OR @id IS NULL;