Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 按逗号分隔的nvchar ID筛选ID_Sql - Fatal编程技术网

Sql 按逗号分隔的nvchar ID筛选ID

Sql 按逗号分隔的nvchar ID筛选ID,sql,Sql,假设我有一个简单的表,其中包含Id(主键)和Name行。 现在我有一个逗号分隔的ID列表,如-2,5,6。我只想获取这些逗号分隔的id,然后将每个id与现有数据进行比较。并且只返回那个些唯一的ID,这意味着数据库中不存在这些ID。请注意,输出也应与输入格式相同,即逗号分隔格式。我正在使用Microsoft SQL server 2017 我已经试过了,就像下面这样: select * from DemoTable where Id 2,5,6 not in DemoTable 但这似乎不是正确

假设我有一个简单的表,其中包含
Id
(主键)和
Name
行。
现在我有一个逗号分隔的ID列表,如-
2,5,6
。我只想获取这些逗号分隔的id,然后将每个id与现有数据进行比较。并且只返回那个些唯一的ID,这意味着数据库中不存在这些ID。请注意,输出也应与输入格式相同,即逗号分隔格式。我正在使用Microsoft SQL server 2017

我已经试过了,就像下面这样:

select * from DemoTable where Id 2,5,6 not in DemoTable

但这似乎不是正确的语法。我如何修理它?

您可以用这个。你需要从另一个角度看待这个问题。我觉得很有趣

实际上,您有一个id的列表作为基础,并且您希望从一些表中不存在的字符串中排除id。所以首先我们需要找到id的列表,然后我们将从表的id中排除它们,以获得我们想要的结果。最后,您可以使用
stuff
string\u agg
将最终结果转换为
分隔字符串

select Value from (
select value from string_split('1,2,3',',')) as t 
where t.value not in (select id from demotable)

您可以查看此链接查看工作小提琴。

这是您的查询

select string_agg(val, ',') as result
from (
    select value as val from string_split('1,2,3',',')) as t 
where t.val not in (select id from tableA)
结果:(逗号分隔)


select*from demograble where Id not in(2,5,6)
“请注意,输出也应与like input格式相同,即逗号分隔格式。”,应为“1,2,3”,对吗?您很接近,但我只想获得我提供的列表2,5,6中唯一的Id的输出。假设5存在,那么它将只返回2,6,类似于您是SQL之王!非常感谢我亲爱的兄弟。作品
1,2,3