Sql Server Nested Inserts possible

↘锁芯ラ 提交于 2021-02-11 13:57:41

问题


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:

  1. Persons table -> ID, FName, SName, DOB
  2. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!