进入我有具有以下值的表:的SQL Server:搜索值没有在表
ID | Name
---------------
1 | Anavaras
2 | Lamurep
我需要一个查询,输出不具有的表项的值。
对于e.g:
如果我的where子句包含id in('1','2','3','4')
,应该产生输出有
3 |
4 |
在表上面的条目。
进入我有具有以下值的表:的SQL Server:搜索值没有在表
ID | Name
---------------
1 | Anavaras
2 | Lamurep
我需要一个查询,输出不具有的表项的值。
对于e.g:
如果我的where子句包含id in('1','2','3','4')
,应该产生输出有
3 |
4 |
在表上面的条目。
你干脆把它变成“派生表”,并使用left join
或类似的结构:
select v.id
from (values(1), (2), (3), (4)) v(id) left join
t
on t.id = v.id
where t.id is null;
事情是这样的:
"SELECT id FROM table WHERE name IS NULL"
我会承担?
首先,你需要分割你的in
到表中。样本分割功能在这里:
CREATE FUNCTION [dbo].[split]
(
@str varchar(max),
@sep char
)
RETURNS
@ids TABLE
(
id varchar(20)
)
AS
BEGIN
declare @pos int,@id varchar(20)
while len(@str)>0
begin
select @pos = charindex(@sep,@str + @sep)
select @id = LEFT(@str,@pos),@str = SUBSTRING(@str,@pos+1,10000000)
insert @ids(id) values(@id)
end
RETURN
END
然后你可以使用这个功能。
select id from dbo.split('1,2,3,4,5',',') ids
left join myTable t on t.id=ids.id
where t.id is null
-- if table ID is varchar then '''1'',''2'',''3'''
修正值constructor'希望你不介意在'表的错误;) –
我不擅长查询..但你使用的概念派生表和表值构造是amazing..Is有什么好的网站来学习像这样的新概念。 –
@prdp。 。 。非常感谢你。 –