我想查询特定值的结果集:
DECLARE @validIds;
SET @validIds = (SELECT id FROM client WHERE valid = 1);
IIF(@id IN @validIds, 1, 0)
这显然不起作用,最好的方法是什么?
如果我有以下"客户"表:
id | valid
1 | 0
2 | 1
3 | 1
当@id为1时,我希望IIF解析为0。
当@id为2或3时,我希望IIF解析为1。
答案 0 :(得分:1)
创建一个表变量来保存有效的ID。如果你的@id变量在有效id列表中,则返回1 - 如果不返回0。
DECLARE @validIds TABLE (id INT);
INSERT INTO @validIds (id) SELECT id FROM clients WHERE VALID = 1;
SELECT ISNULL((SELECT 1 from @validIds where @id = id), 0);
答案 1 :(得分:1)
这将生成您想要的输出:
SELECT ID, CASE WHEN ID = 1 THEN 0 ELSE 1 END AS VALID FROM client
答案 2 :(得分:0)
DECLARE @validIds table (id int);
INSERT INTO @validIds VALUES (1),(2),(3)
DECLARE @Client table (id int);
INSERT INTO @Client VALUES (1),(2),(3),(4),(5)
SELECT c.id AS Client_ID
,CASE WHEN EXISTS (SELECT 1 FROM @validIds WHERE id = c.id)
THEN 1 ELSE 0 END AS [Valid_ID]
FROM @Client c
╔═══════════╦══════════╗
║ Client_ID ║ Valid_ID ║
╠═══════════╬══════════╣
║ 1 ║ 1 ║
║ 2 ║ 1 ║
║ 3 ║ 1 ║
║ 4 ║ 0 ║
║ 5 ║ 0 ║
╚═══════════╩══════════╝