Sql 如何查找表中不存在的ID

Sql 如何查找表中不存在的ID,sql,sql-server,stored-procedures,comma,Sql,Sql Server,Stored Procedures,Comma,我的SP的输入参数为@serviceIds=1,2,3,4,5,6,7,8;。输入参数由逗号分隔的ID组成。我有一张叫服务台的桌子 我需要检查表中是否存在这些特定ID。我怎么做? 根据上面的例子,我需要这个逗号分隔的输出。6,7,8STRING\u SPLIT将使用分隔符将字符串拆分为一个表,STRING\u AGG将select语句的所有行合并为一个字符串 Declare @serviceIds as varchar(max) = '1,10,3,4,5,6,7,8' Select

我的SP的输入参数为@serviceIds=1,2,3,4,5,6,7,8;。输入参数由逗号分隔的ID组成。我有一张叫服务台的桌子

我需要检查表中是否存在这些特定ID。我怎么做? 根据上面的例子,我需要这个逗号分隔的输出。6,7,8

STRING\u SPLIT将使用分隔符将字符串拆分为一个表,STRING\u AGG将select语句的所有行合并为一个字符串

Declare @serviceIds as varchar(max) = '1,10,3,4,5,6,7,8'

Select
    STRING_AGG([value],',') as Result
from STRING_SPLIT (@serviceIds , ',' )
Where [value] not in (Select ServiceID from [service])
您可以使用“不存在”和“字符串分割”:

您无法控制传递到存储过程中的值,因此这将使用try\u convert来防止转换错误-假设比较列是一个数字

编辑:

如果愿意,可以重新聚合这些值:

select string_agg(ss.value, ',') within group (order by ss.value)
from string_split(@serviceids, ',') ss
where not exists (select 1
                  from service s
                  where try_convert(int, ss.value) = s.id
                 );

您使用的是哪个版本的SQL Server?@Adam,检查我的答案。它工作得很好,速度也很快。我不知道是谁把它标记为无用。你能告诉我如何将这个输出作为逗号分隔的字符串吗?因为它当前返回为表。我需要逗号分隔字符串我尝试过,它显示以下错误字符串\u AGG'不是可识别的内置函数名。我正在使用SQL SERVER 2016检查数据库的兼容性级别。从sys.databases中选择名称、兼容性和级别;应该是13。如果不改变数据库,则数据库集兼容性\u LEVEL=130;去
select ss.value
from string_split(@serviceids, ',') ss
where not exists (select 1
                  from service s
                  where try_convert(int, ss.value) = s.id
                 );
select string_agg(ss.value, ',') within group (order by ss.value)
from string_split(@serviceids, ',') ss
where not exists (select 1
                  from service s
                  where try_convert(int, ss.value) = s.id
                 );