我正在尝试根据逗号分隔值查询表。如果存在值,我需要使用。如果它是空的我需要选择所有
DECLARE @UserIdList VARCHAR(500) = '150, 112' // Not working when its ''
DECLARE @Users TABLE (UserId INT);
WITH UserCSVtoTable AS
(
SELECT
CAST('<XMLRoot><RowData>' + REPLACE(t.val, ',', '</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
FROM
(SELECT @UserIdList) AS t(val)
)
INSERT INTO @Users (UserId)
SELECT m.n.value('.[1]', 'varchar(8000)') AS UserId
FROM UserCSVtoTable
CROSS APPLY x.nodes('/XMLRoot/RowData') m(n)
查询
SELECT UserId, Email
FROM Users
WHERE UserId IN (SELECT UserId FROM @Users)
仅在我发送值时才有效。如果我发送''它没有记录所有记录。
如果@Users
列表中没有可用的记录,如何获取所有记录?
答案 0 :(得分:2)
您可以使用:
SELECT UserId, Email
From Users
Where UserId IN (Select UserId from @Users)
OR NOT EXISTS(SELECT 1 FROM @Users);
假设UserId
被定义为NOT NULL
,则两个条件都是互斥的。