AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / dba / Perguntas / 187091
Accepted
Darrell
Darrell
Asked: 2017-09-28 11:59:44 +0800 CST2017-09-28 11:59:44 +0800 CST 2017-09-28 11:59:44 +0800 CST

Como adiciono vários novos registros com base nos antigos

  • 772

Ok, todos vocês, pessoas inteligentes, me ajudem a descobrir isso.

Eu tenho um conjunto de tabelas relacionadas para pesquisas que estamos fazendo:

dbo.Surveys
------------
| SurveyID |
------------
| 1        |
------------

dbo.Questions
-------------------------
| SurveyID | QuestionID |
-------------------------
| 1        | 1          |
-------------------------
| 1        | 2          |
-------------------------
| 1        | 3          |
-------------------------

dbo.Offerings
--------------------------------------
| SurveyID | QuestionID | OfferingID |
--------------------------------------
| 1        | 1          | 1          |
--------------------------------------
| 1        | 3          | 2          |
--------------------------------------

Fatos:

dbo.Surveys.SurveyID é IDENTIDADE

dbo.Questions.QuestionID é IDENTITY

dbo.Offerings.OfferingID é IDENTITY

Preciso criar uma nova pesquisa com base em uma cópia de uma já existente.

Recebo uma cópia do SurveyID 1 e insiro-o em dbo.Surveys, em seguida, recebo o novo SurveyID.

Recebo uma cópia de todas as perguntas relacionadas ao SurveyID 1 e as insiro em dbo.Questions e altero o SurveyID para o novo.

Isso, obviamente, gera um novo QuestionID para cada registro.

Recebo uma cópia de todas as ofertas relacionadas ao SurveyID 1 e as insiro em dbo.Offerings e altero o SurveyID para o novo.

O truque agora é: como saber qual novo OfferID combina com qual novo QuestionID para que eu possa atualizar o QuestionID na tabela dbo.Offerings?

Então, para aprofundar isso, é isso que eu acabo com:

dbo.Surveys
------------
| SurveyID |
------------
| 1        |
------------
| 2        |
------------

dbo.Questions
-------------------------
| SurveyID | QuestionID |
-------------------------
| 1        | 1          |
-------------------------
| 1        | 2          |
-------------------------
| 1        | 3          |
-------------------------
| 2        | 4          |
-------------------------
| 2        | 5          |
-------------------------
| 2        | 6          |
-------------------------

dbo.Offerings
--------------------------------------
| SurveyID | QuestionID | OfferingID |
--------------------------------------
| 1        | 1          | 1          |
--------------------------------------
| 1        | 3          | 2          |
--------------------------------------
| 2        | 1          | 3          | (QuestionID needs to be 4)
--------------------------------------
| 2        | 3          | 4          | (QuestionID needs to be 6)
--------------------------------------

EDIT: Ok. A título de esclarecimento:

CREATE TABLE Survey (SurveyID int identity, sname varchar(30));
CREATE TABLE Questions (QuestionID int IDENTITY, SurveyID int, qtext varchar(30), qtype varchar(20));
CREATE TABLE Offerings (OfferingID int IDENTITY, QuestionID int, SurveyID int, ovalues varchar(30));

INSERT INTO Survey VALUES ('New Survey');
INSERT INTO Questions VALUES (1,'Enter text','SingleAnswer');
INSERT INTO Questions VALUES (1,'Pick one','MultipleChoice');
INSERT INTO Offerings VALUES (2,1,'Choice 1');
INSERT INTO Offerings VALUES (2,1,'Choice 2');
INSERT INTO Offerings VALUES (2,1,'Choice 3');

SELECT * FROM Survey;
SELECT * FROM Questions;
SELECT * FROM Offerings;

    SurveyID | sname
    ---------------------
           1 | New Survey

    QuestionID | SurveyID | qtext      | qtype
    ---------------------------------------------------
             1 |        1 | Enter text | SingleAnswer
             2 |        1 | Pick one   | MultipleChoice

    OfferingID | QuestionID | SurveyID | ovalues
    ---------------------------------------------
             1 |          2 |        1 | Choice 1
             2 |          2 |        1 | Choice 2
             3 |          2 |        1 | Choice 3

Então, agora eu preciso de uma cópia do SurveyID 1 tal que:

    SurveyID | sname
    -----------------------
           1 | New Survey
           2 | New Survey 2

    QuestionID | SurveyID | qtext      | qtype
    ---------------------------------------------------
             1 |        1 | Enter text | SingleAnswer
             2 |        1 | Pick one   | MultipleChoice
             3 |        2 | Enter text | SingleAnswer
             4 |        2 | Pick one   | MultipleChoice

    OfferingID | QuestionID | SurveyID | ovalues
    ---------------------------------------------
             1 |          2 |        1 | Choice 1
             2 |          2 |        1 | Choice 2
             3 |          2 |        1 | Choice 3
             4 |          4 |        2 | Choice 1
             5 |          4 |        2 | Choice 2
             6 |          4 |        2 | Choice 3
t-sql
  • 2 2 respostas
  • 70 Views

2 respostas

  • Voted
  1. markp-fuso
    2017-09-28T16:35:17+08:002017-09-28T16:35:17+08:00

    Resposta à pergunta original


    Deixando de lado por enquanto que a) não sabemos o que get a copy of ...implica eb) não temos o DDL para as tabelas em questão (por exemplo, definições de PK) ... teremos que improvisar um pouco ...

    Começaremos com algumas tabelas e dados de amostra:

    drop table if exists Surveys
    drop table if exists Questions
    drop table if exists Offerings;
    
    create table Surveys
    (SurveyID    int           identity
    ,sname       varchar(30)
    );
    
    create table Questions
    (SurveyID    int
    ,QuestionID  int           identity
    ,qtext       varchar(max)
    );
    
    create table Offerings
    (SurveyID    int
    ,QuestionID  int
    ,OfferingID  int            identity
    ,otext       varchar(max)
    );
    
    -- populate the tables
    
    declare @new_sid int
    
    insert into Surveys (sname) select 'Survey ABC'
    
    select @new_sid = @@identity
    
    insert into Questions (SurveyID, qtext) values 
    (@new_sid, 'Quest_#1'), 
    (@new_sid, 'Quest_#2'), 
    (@new_sid, 'Quest_#3')
    
    -- just pick 2 questions to work with; min()/max() will suffice
    
    insert into Offerings (SurveyID, QuestionID, otext) 
    select @new_sid,min(QuestionID),'Off_#1' from Questions where SurveyID = @new_sid
    union all
    select @new_sid,max(QuestionID),'Off_#2' from Questions where SurveyID = @new_sid;
    
    -- review our new data
    
    select * from Surveys   order by SurveyID
    select * from Questions order by SurveyID, QuestionID
    select * from Offerings order by SurveyID, QuestionID, OfferingID;
    
     SurveyID | sname     
     -------- | ----------
            1 | Survey ABC
    
     SurveyID | QuestionID | qtext    
     -------- | ---------- | ---------
            1 |          1 | Quest_#1 
            1 |          2 | Quest_#2 
            1 |          3 | Quest_#3
    
     SurveyID | QuestionID | OfferingID | otext 
     -------- | ---------- | ---------- | ------
            1 |          1 |          1 | Off_#1
            1 |          3 |          2 | Off_#2
    

    Para este exemplo, afirmaremos que copysignifica duplicar o mesmo número de linhas (Pesquisa, Perguntas, Ofertas) e anexar todos os nossos valores de texto com ' (versão_#2)':

    declare @old_sid int,
            @new_sid int
    
    -- find our old SurveyID
    
    select @old_sid = SurveyID from Surveys where sname = 'Survey ABC'
    
    -- create our new Survey, appending '(version_#2)' to stext
    
    insert into Surveys (sname) 
    select sname + ' (version_#2)' from Surveys where SurveyID = @old_sid
    
    -- grab the new SurveyID
    
    select @new_sid = @@identity
    
    -- copy our old Survey's Questions, replacing the old SurveyID with the new SurveyID,
    -- and append ' (version_#2)' to the qtext field
    
    insert into Questions (SurveyID, qtext) 
    select @new_sid, 
           q.qtext + ' (version_#2)' 
    from   Questions q
    where  q.SurveyID = @old_sid;
    
    -- use a couple CTEs to pull our old Questions/Offerings and new Questions;
    -- without any input on how to map the old and new data sets we'll generate
    -- a row_number() column with each data set, with the objective being to 
    -- join the old/new data sets by matching row numbers
    
    with
    oldtab as
    (select  row_number() over(order by q.QuestionID) as rnum, 
             o.otext
     from    Questions q 
     left 
     join    Offerings o
     on      q.SurveyID   = o.SurveyID
     and     q.QuestionID = o.QuestionID
     where   q.SurveyID   = @old_sid),
    
    newtab as
    (select  row_number() over(order by q.QuestionID) as rnum, 
             q.SurveyID, 
             q.QuestionID
     from    Questions q 
     where   q.SurveyID   = @new_sid)
    
    -- insert our new SurveyID/QuestionID pairs, and the old otext values
    
    insert into Offerings (SurveyID, QuestionID, otext) 
    
    select   n.SurveyID,
             n.QuestionID,
             o.otext + ' (version_#2)'
    from     oldtab o
    join     newtab n
    on       o.rnum = n.rnum       -- join by row_number()
    where    o.otext is NOT NULL   -- skip (old) Questions that didn't have a matching row in Offerings
    order by o.rnum
    

    E os resultados:

    select * from Surveys   order by SurveyID
    select * from Questions order by SurveyID, QuestionID
    select * from Offerings order by SurveyID, QuestionID, OfferingID
    
     SurveyID | sname                 
     -------- | ----------------------
            1 | Survey ABC            
            2 | Survey ABC (version_#2)
    
     SurveyID | QuestionID | qtext               
     -------- | ---------- | --------------------
            1 |          1 | Quest_#1            
            1 |          2 | Quest_#2            
            1 |          3 | Quest_#3            
            2 |          4 | Quest_#1 (version_#2)
            2 |          5 | Quest_#2 (version_#2)
            2 |          6 | Quest_#3 (version_#2)
    
     SurveyID | QuestionID | OfferingID | otext              
     -------- | ---------- | ---------- | -------------------
            1 |          1 |          1 | Off_#1             
            1 |          3 |          2 | Off_#2             
            2 |          4 |          3 | Off_#1 (version_#2)
            2 |          6 |          4 | Off_#2 (version_#2)
    

    Aqui está um dbfiddle do acima.

    • 2
  2. Best Answer
    markp-fuso
    2017-09-29T13:26:33+08:002017-09-29T13:26:33+08:00

    Resposta à pergunta atualizada/editada (adição de colunas qtext/qtype/ovalues)


    Usando o mesmo create tablee os insertcomandos da parte editada da pergunta, reutilizaremos parte do código da minha resposta original ...

    declare @old_sid int,
            @new_sid int
    
    select @old_sid = SurveyID from Survey where sname = 'New Survey'
    
    -- create new Survey record
    
    insert into Survey (sname) 
    select sname + ' 2' from Survey where SurveyID = @old_sid
    
    select @new_sid = @@identity
    
    -- create new Questions records
    
    insert into Questions (SurveyID, qtext, qtype) 
    select @new_sid, 
           q.qtext,
           q.qtype
    from   Questions q
    where  q.SurveyID = @old_sid;
    
    -- create new Offerings records
    
    with
    qmap as
    (-- build a mapping between old and new QuestionID/SurveyID pairs
     select o.QuestionID as oldQID,
            o.SurveyID   as oldSID,
            n.QuestionID as newQID,
            n.SurveyID   as newSID,
            n.qtext,
            n.qtype
    
    from    Questions o
    join    Questions n
    
    on      o.qtext = n.qtext
    and     o.qtype = n.qtype
    and     o.SurveyID = @old_sid
    and     n.SurveyID = @new_sid)
    
    insert into Offerings (QuestionID, SurveyID, ovalues)
    
    select  m.newQID,
            m.newSID,
            o.ovalues
    
    from    Offerings o
    join    qmap m
    
    on      o.QuestionID = m.oldQID
    and     o.SurveyID   = m.oldSID
    and     o.SurveyID   = @old_sid;
    

    NOTA: Provavelmente poderia rolar esta qmapsolução na minha resposta à pergunta original, mas optando por deixar a resposta original como está por enquanto.

    E os resultados:

    select * from Survey    order by SurveyID
    select * from Questions order by SurveyID, QuestionID
    select * from Offerings order by SurveyID, QuestionID, OfferingID
    
     SurveyID | sname       
     -------- | ------------
            1 | New Survey  
            2 | New Survey 2
    
     QuestionID | SurveyID | qtext      | qtype         
     ---------- | -------- | ---------- | --------------
              1 |        1 | Enter text | SingleAnswer  
              2 |        1 | Pick one   | MultipleChoice
              3 |        2 | Enter text | SingleAnswer  
              4 |        2 | Pick one   | MultipleChoice
    
     OfferingID | QuestionID | SurveyID | ovalues 
     ---------- | ---------- | -------- | --------
              1 |          2 |        1 | Choice 1
              2 |          2 |        1 | Choice 2
              3 |          2 |        1 | Choice 3
              4 |          4 |        2 | Choice 1
              5 |          4 |        2 | Choice 2
              6 |          4 |        2 | Choice 3
    

    Aqui está um dbfiddle para o acima.

    • 0

relate perguntas

  • Como alterar as configurações do gerenciador de configuração do servidor SQL usando o TSQL?

  • Como posso obter uma lista de nomes e tipos de coluna de um conjunto de resultados?

  • MS SQL: Use o valor calculado para calcular outros valores

  • Como posso saber se um banco de dados SQL Server ainda está sendo usado?

  • Implementando uma consulta PIVOT

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host

    • 12 respostas
  • Marko Smith

    Como fazer a saída do sqlplus aparecer em uma linha?

    • 3 respostas
  • Marko Smith

    Selecione qual tem data máxima ou data mais recente

    • 3 respostas
  • Marko Smith

    Como faço para listar todos os esquemas no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Listar todas as colunas de uma tabela especificada

    • 5 respostas
  • Marko Smith

    Como usar o sqlplus para se conectar a um banco de dados Oracle localizado em outro host sem modificar meu próprio tnsnames.ora

    • 4 respostas
  • Marko Smith

    Como você mysqldump tabela (s) específica (s)?

    • 4 respostas
  • Marko Smith

    Listar os privilégios do banco de dados usando o psql

    • 10 respostas
  • Marko Smith

    Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Como faço para listar todos os bancos de dados e tabelas usando o psql?

    • 7 respostas
  • Martin Hope
    Jin conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host 2014-12-02 02:54:58 +0800 CST
  • Martin Hope
    Stéphane Como faço para listar todos os esquemas no PostgreSQL? 2013-04-16 11:19:16 +0800 CST
  • Martin Hope
    Mike Walsh Por que o log de transações continua crescendo ou fica sem espaço? 2012-12-05 18:11:22 +0800 CST
  • Martin Hope
    Stephane Rolland Listar todas as colunas de uma tabela especificada 2012-08-14 04:44:44 +0800 CST
  • Martin Hope
    haxney O MySQL pode realizar consultas razoavelmente em bilhões de linhas? 2012-07-03 11:36:13 +0800 CST
  • Martin Hope
    qazwsx Como posso monitorar o andamento de uma importação de um arquivo .sql grande? 2012-05-03 08:54:41 +0800 CST
  • Martin Hope
    markdorison Como você mysqldump tabela (s) específica (s)? 2011-12-17 12:39:37 +0800 CST
  • Martin Hope
    Jonas Como posso cronometrar consultas SQL usando psql? 2011-06-04 02:22:54 +0800 CST
  • Martin Hope
    Jonas Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL? 2011-05-28 00:33:05 +0800 CST
  • Martin Hope
    Jonas Como faço para listar todos os bancos de dados e tabelas usando o psql? 2011-02-18 00:45:49 +0800 CST

Hot tag

sql-server mysql postgresql sql-server-2014 sql-server-2016 oracle sql-server-2008 database-design query-performance sql-server-2017

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve