日期:2014-05-17 浏览次数:20553 次
if object_id('Tempdb..#table1') is not null drop table #table1
if object_id('Tempdb..#table2') is not null drop table #table2
create table #table1(
id int identity(1,1) not null,
a nvarchar(100) null,
b nvarchar(100) null
)
create table #table2(
id int identity(1,1) not null,
a nvarchar(100) null,
b nvarchar(100) null
)
Insert Into #table1
select 'a','b' union all
select 'c','d' union all
select 'e','f' union all
select 'g','h'
Insert Into #table2
select 'a','b' union all
select 'c','d' union all
select 'e','s' union all
select 'g','h'
--查询相同数据
;with cte_a as (
select t.id from #table2 t
join #table1 s on s.a=t.a and s.b=t.b
)
--查询table1不存在的数据
,cte_b as(
select * from #table2 where id not in(select id from cte_a)
)
--插入
Insert into #table1
select a,b from cte_b
--查询Insert 结果
select * from #table1
---------------------------------------
--------结果
id a b