/*
批量插入表值,SQL方法
本方是从table02里取值,并且这些值在table01表不存在,把这些不存在的值直接插入table01的样例
以博高手一笑。
*/
create table table01
(
f1 varchar(255) default '',
f2 varchar(255) default '',
f3 varchar(255) default '',
f4 varchar(255) default ''
)
go
create unique index Unique_Index01 on table01 (f1,f2)
go
create table table02
(
f1 varchar(255) default '',
f2 varchar(255) default '',
f3 varchar(255) default '',
f4 varchar(255) default ''
)
go
create unique index Unique_Index01 on table02 (f1,f2)
go
--插入样例数据
declare @i int
insert table01(f1,f2,f3,f4) values('1','','','')
insert table01(f1,f2,f3,f4) values('2','','','')
insert table01(f1,f2,f3,f4) values('3','','','')
insert table02(f1,f2,f3,f4) values('1','','','')
insert table02(f1,f2,f3,f4) values('2','','','')
insert table02(f1,f2,f3,f4) values('3','','','')
insert table02(f1,f2,f3,f4) values('4','','','')
insert table02(f1,f2,f3,f4) values('5','','','')
insert table02(f1,f2,f3,f4) values('6','','','')
go
--左联接意思是仅显示table02表里与table01表里相等的值。
--如果在table01表里没有,则F5,F6,F7,F8 为 null
select table02.f1 ,table02.f2,table02.f3,table02.f4,
table01.f1 as F5 ,table01.f2 as F6,table01.f3 as F7,table01.f4 as F8
from table02
left join table01 on table02.f1 = table01.f1 and table02.f2 = table01.f2
go
--把上面的左连接的结果看作一个整体tx。查询出所有F5,F6,F7,F8为null的结果
select *
from
(
select table02.f1 ,table02.f2,table02.f3,table02.f4,
table01.f1 as F5 ,table01.f2 as F6,table01.f3 as F7,table01.f4 as F8
from table02
left join table01 on table02.f1 = table01.f1 and table02.f2 = table01.f2
) tx
where tx.F5 is null
go
/*把结果插入table01*/
insert table01
(f1,f2,f3,f4)
select tx.f1,tx.f2,tx.f3,tx.f4
from
(
select table02.f1 ,table02.f2,table02.f3,table02.f4,
table01.f1 as F5 ,table01.f2 as F6,table01.f3 as F7,table01.f4 as F8
from table02
left join table01 on table02.f1 = table01.f1 and table02.f2 = table01.f2
) tx
where tx.F5 is null
go
select * from table01
go
drop table table01
drop table table02