2012-04-27 65 views
8

存在我需要知道是否还有其它的从一个表中的所有行:的SQL Server:检查是否所有行的其它表

declare @Table1 table (id int) 
declare @Table2 table (id int) 

insert into @Table1(id) values (1) 
insert into @Table1(id) values (4) 
insert into @Table1(id) values (5) 


insert into @Table2(id) values (1) 
insert into @Table2(id) values (2) 
insert into @Table2(id) values (3) 

if exists (select id from @Table1 where id in (select id from @Table2)) 
    select 'yes exists' 
else 
    select 'no, doesn''t exist' 

该查询返回yes exists但应返​​回no, doesn't exist因为只有1 @Table2存在,值4和5不会。

我应该在查询中更改哪些内容?谢谢!

+0

HM,是的,我需要布尔结果来验证,从第一个表中的所有行中第二个表中存在(或没有) – ihorko 2012-04-27 15:50:31

回答

8
IF NOT EXISTS (
    SELECT ID FROM @Table1 
    EXCEPT 
    SELECT ID FROM @Table2 
) 
SELECT 'yes exists' 
ELSE SELECT 'no, doesn''t exist' 
+0

完美,谢谢! – ihorko 2012-04-27 16:09:48

0
select case when count(*) > 0 then 'no' else 'yes' end as AllExist 
from @Table1 t1 
left outer join @Table2 t2 on t1.id = t2.id 
where t2.id is null 
0

这会工作,只要这两个ID列是唯一的(他们应该是,如果他们的ID)

DECLARE @totalRows int; 
SET @totalRows = SELECT count(*) from Table1; 

RETURN (@totalRows == SELECT count(*) from Table1 JOIN Table2 on Table1.id = Table2.id) 
2

你可以使用EXCEPT得到两个表的差集。如果返回任何ID的,两个表是不相等的:

SELECT ID 
FROM @Table1 
EXCEPT 
SELECT ID 
FROM @Table2 

EXCEPT返回从左边查询是不是也右边查询发现任何不同的值。

所以,让你的“没有,那并不存在”

;WITH diff AS(
    SELECT ID 
    FROM @Table1 
    EXCEPT 
    SELECT ID 
    FROM @Table2 
) 
SELECT CASE WHEN COUNT(diff.ID) = 0 
     THEN 'yes exists' 
     ELSE 'no, doesnt exist' 
     END AS Result 
FROM diff 
相关问题