如何在sql server的其他表中找到表的完整或Nill或部分表示?

时间:2015-05-26 07:22:46

标签: sql sql-server tsql

Create table #Table1  (id int)
Create table #Table2  (id int)

--Table1 insertion
insert into #Table1(id) values (5)
insert into #Table1(id) values (1)
insert into #Table1(id) values (2)

--Table2 insertion
insert into #Table2(id) values (5)
insert into #Table2(id) values (6)
insert into #Table2(id) values (7)

我想评估三个条件:

  1. Table1

  2. Table2是否完全存在
  3. Table1并非Table2中完全存在(交叉点什么都不是)

  4. Table1部分存在于Table2

  5. 我该怎么做?

1 个答案:

答案 0 :(得分:0)

这是怎么回事?

begin tran

Create table #Table1  (id int)
Create table #Table2  (id int)

--Table1 insertion
insert into #Table1(id) values (5)
insert into #Table1(id) values (1)
insert into #Table1(id) values (2)

--Table2 insertion
insert into #Table2(id) values (5)
insert into #Table2(id) values (6)
insert into #Table2(id) values (7)

select case when exists (
    select 1
    from #Table1 t1
    where not exists(select 1 from #Table2 t2 where t1.id = t2.id)
) then 0 else 1 end as Table1IsFullyInTable2

select case when exists (
    select 1
    from #Table1 t1
    where not exists(select 1 from #Table2 t2 where t1.id = t2.id)
) then 1 else 0 end as Table1DoesNotExistFullyInTable2

select case when exists (
    select 1
    from #Table1 t1
    where exists(select 1 from #Table2 t2 where t1.id = t2.id)
) then 1 else 0 end as Table1ParitiallyInTable2

rollback tran