SQL:将数据从一个表插入到两个相互关联的表中
我有一个表tSource,它是笛卡尔积的SELECT结果,所以在集合中没有唯一的ID。总之可以说,该表如下所示:SQL:将数据从一个表插入到两个相互关联的表中
tSource
-------
f1 | f2
-------
H | a
I | b
J | c
K | d
K | d
我需要“分裂”的tSource的数据为TBL1和TBL2它们的相互关系:两个
tbl1 tbl2
------- -----------------
ID | f1 ID | tbl1_ID | f2
------- -----------------
11 | H 51 | 11 | a
12 | I 52 | 12 | b
13 | J 53 | 13 | c
14 | K 54 | 14 | d
15 | K 55 | 15 | d
ID列目标表是INT IDENTITY
任何帮助,将不胜感激, thanx提前
在MERGE + OUTPUT语句中完成两个插入操作。
merge @table2 as t2
using (
select *
from @table
) as src
on (1 = 2)
when not matched then
insert (f1)
values (src.f1)
output inserted.ID, src.f2 into @table3 (f1ID, f2)
;
完整的例子:
declare @table table (
f1 char(1)
, f2 char(1)
)
insert @table
values
('H', 'a')
, ('I', 'b')
, ('J', 'c')
, ('K', 'd')
declare @table2 table (
ID int not null identity
, f1 char(1)
)
declare @table3 table (
ID int not null identity
, f1ID int not null
, f2 char(1)
)
merge @table2 as t2
using (
select *
from @table
) as src
on (1 = 2)
when not matched then
insert (f1)
values (src.f1)
output inserted.ID, src.f2 into @table3 (f1ID, f2)
;
select *
from @table2
select *
from @table3
这不是intirely正确的SQL(因为我不知道日E型产品),但我想你会明白我的意思
create table tbl1(ID primary key identity, f1, f2)
insert into tbl1(f1, f2) select f1, f2 from tSource
create table tbl2(ID primary key identity, tbl1_ID not null, f2)
insert into tbl2(tbl1_ID, f2) select ID, f2 from tbl1
alter table tbl1 drop column f2
alter table tbl2 add constraint myForeignKey foreignkey(tabl1_ID) references tbl1(ID)
Part1-:
insert into tbl1(f1) select f1 from tSource;
Part2-:
Insert into Tabl2 (tbl1_id,f2)
(
Select id,f2 from (Select Row_Number() Over(Partition by id order by id) as row,t1.f2,t2.id from t1 ,t2) a
where row=(Select r from
(Select Row_Number() over(Order by id)as r,id from t2) b where b.id=a.id)
)
这里什么选择第2部分返回.... SQL Fiddle Demo
必须承认完全忘记了row_number()!谢谢 !!! – armen 2013-05-14 12:04:54
@armen欢迎....它有时会发生.....很高兴它为你赢得 – 2013-05-14 12:05:57
这是最准确的例子,虽然答复由AmitSingh非常快速和可以接受,因为它完成了工作! 我习惯后会开始使用合并方法,因为这对我来说是新东西! – armen 2013-05-14 12:16:01
我想我给了最好的方法恕我直言,但如果你真的想去其他(不保证工作)的方式,那么做。一个人通常知道在插入多行时不应该依赖IDENTITY排序。 – Serge 2013-05-14 12:20:04
经过重度测试后,我迁移到MERGE方法。唯一的问题是,如果两个目标表是主/外部合并失败输出到部分,但我用一个@temp表克服它 – armen 2013-05-14 14:10:57