INSERT in two Tables based on SELECT

0

Imagine the following scenario:

At some point you need to duplicate people and their items.

If I have the following data:

Person Table

+----+------------+
| Id | Nome       |
+----+------------+
| 1  | Joãozinho  |
| 2  | Mariazinha |
+----+------------+

PersonItem Table

+----+------------+--------+
| Id | PessoaId   | ItemId |
+----+------------+--------+
| 1  | 1          | 1      |
| 2  | 1          | 2      |
| 3  | 2          | 1      |
+----+------------+--------+

Table Item

+----+------------+
| Id | Descricao  |
+----+------------+
| 1  | Item1      |
| 2  | Item2      |
+----+------------+

It can be concluded that Joãozinho has Item1 and Item2 , and Mariazinha has only Item1 .

Duplicating the data, we would have:

Person Table

+----+------------+
| Id | Nome       |
+----+------------+
| 1  | Joãozinho  |
| 2  | Mariazinha |
| 3  | Joãozinho  |
| 4  | Mariazinha |
+----+------------+

PersonItem Table

+----+------------+--------+
| Id | PessoaId   | ItemId |
+----+------------+--------+
| 1  | 1          | 1      |
| 2  | 1          | 2      |
| 3  | 2          | 1      |
| 4  | 3          | 1      |
| 5  | 3          | 2      |
| 6  | 4          | 1      |
+----+------------+--------+

Table Item It remains as before.

To duplicate just one table is easy, just run the following script:

INSERT INTO Pessoa
(Nome)
SELECT Nome
FROM Pessoa

But in this case, which involves more than one table? What is the best way to do this?

  

I'm using SQL Server.

    
asked by anonymous 02.03.2017 / 20:27

1 answer

1
DECLARE @campo VARCHAR(30)
    , @campo2 VARCHAR(30)
    , @campo3 VARCHAR(60)

-- Cursor para percorrer os nomes dos objetos 
DECLARE itens CURSOR FOR
    SELECT campo, campo2, campo3 
    FROM
        tabela_origem


-- Abrindo Cursor para leitura
OPEN itens

-- Lendo a próxima linha
FETCH NEXT FROM itens INTO @campo, @campo2, @campo3

-- Percorrendo linhas do cursor (enquanto houverem)
WHILE @@FETCH_STATUS = 0
BEGIN

    INSERT INTO TABELA2 VALUES( @campo, @campo2, @campo3 )

    -- Lendo a próxima linha
  FETCH NEXT FROM itens INTO @campo, @campo2, @campo3
END

-- Fechando Cursor para leitura
CLOSE itens

-- Desalocando o cursor
DEALLOCATE itens
    
02.03.2017 / 20:49