问题
I have data in flatfile structure which I need to Insert into two tables. The structure is:
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
The two tables where the above data will be inserted:
- Persons table -> ID, FName, SName, DOB
- PersonsRelations table -> ID, Response, Description where Response1, 2 etc is NOT NULL.
I have started the tsql query but not sure how to complete/achieve this. The query should read row after row and foreach create a new row in Persons table and insert the related responses & descriptions as new rows in PersonsRelations table. So for example for record with ID = 4 there will be 3 related new row entries in PersonsRelations table.
回答1:
This should do the trick, you can use the APPLY
operator to unpivot a table.
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;
来源:https://stackoverflow.com/questions/27707843/sql-server-nested-inserts-possible