2016-05-07 97 views
0

進入我有具有以下值的表:的SQL Server:搜索值沒有在表

ID | Name 
--------------- 
1 | Anavaras 
2 | Lamurep 

我需要一個查詢,輸出不具有的表項的值。

對於e.g:

如果我的where子句包含id in('1','2','3','4'),應該產生輸出有

3 | 
4 | 

在表上面的條目。

回答

2

你乾脆把它變成「派生表」,並使用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; 
+1

修正值constructor'希望你不介意在'表的錯誤;) –

+0

我不擅長查詢..但你使用的概念派生表和表值構造是amazing..Is有什麼好的網站來學習像這樣的新概念。 –

+0

@prdp。 。 。非常感謝你。 –

0

事情是這樣的:

"SELECT id FROM table WHERE name IS NULL" 

我會承擔?

0

首先,你需要分割你的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'''