我有flatfile结构中的数据,我需要将其插入到两个表中。结构是:
ID FName SName DOB Response1 Description1 Response2 Description2 Response3 Description3
3 Bill John 01/01 Yes Fault NULL NULL NULL NULL
4 Cat Bill 01/01 Yes FaultX Emer FaultYX Zeber Nuhgt
将插入上述数据的两个表:
我已经启动了tsql查询,但不确定如何完成/实现此目的。查询应该逐行读取并且foreach在Persons表中创建一个新行并插入相关的响应&描述为PersonsRelations表中的新行。因此,例如对于ID = 4的记录,PersonsRelations表中将有3个相关的新行条目。
答案 0 :(得分:2)
这应该可以解决问题,您可以使用APPLY
运算符来取消对表格的删除。
create table #tobeinserted
(
ID int,
FName varchar(50),
SName varchar(50),
DOB date,
Response1 varchar(50),
Description1 varchar(50),
Response2 varchar(50),
Description2 varchar(50),
Response3 varchar(50),
Description3 varchar(50)
);
create table #persons
(
ID int,
FName varchar(50),
SName varchar(50),
DOB date
);
create table #personsRelations
(
PersonId int,
Response varchar(50),
Description varchar(50)
);
insert into #tobeinserted (ID,FName,SName,DOB,Response1,Description1,Response2,Description2,Response3,Description3)
values (3,'Bill','John','20140101','Yes','Fault',NULL,NULL,NULL,NULL),
(4,'Cat','Bill','20140101','Yes','FaultX','Emer','FaultYX','Zeber','Nuhgt');
insert into #persons (id,fname,sname,dob)
select id+6000000, fname, sname, dob
from #tobeinserted
insert into #personsRelations (PersonId, Response, Description)
select t.id+6000000, a.response, a.description
from #tobeinserted t
cross apply
(
values(Response1,Description1),(Response2,Description2),(Response3,Description3)
) as a(response, description)
where a.response is not null
select * from #persons;
select * from #personsRelations;
drop table #personsRelations;
drop table #persons;
drop table #tobeinserted;