Sql server SQL Server:检查其他表中是否存在所有行

Sql server SQL Server:检查其他表中是否存在所有行,sql-server,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(

我需要知道一个表中的所有行是否存在于另一个表中:

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' 
此查询返回
yesexists
,但应返回
no,notexists
,因为
@Table2
中只存在1,值4和5不存在


我应该在查询中更改什么?谢谢

只要两个id列都是唯一的(如果它们是id的,则应该是唯一的),这将起作用

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
您可以使用来获取两个表的集差。如果返回任何ID,则两个表不相等:

SELECT ID
FROM @Table1
EXCEPT 
SELECT ID
FROM @Table2
Exception从左侧查询返回在右侧查询中找不到的任何不同值

所以,要得到你的“不,不存在”:


嗯,是的,我需要bool结果来验证第一个表中的所有行是否存在于第二个表中(或者不存在)
IF NOT EXISTS (
    SELECT ID FROM @Table1
    EXCEPT
    SELECT ID FROM @Table2
)
SELECT 'yes exists'
ELSE SELECT 'no, doesn''t exist'
SELECT ID
FROM @Table1
EXCEPT 
SELECT ID
FROM @Table2
;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