1
Imagine the following scenario:
At a certain point it is necessary to duplicate people and their respective items.
If I have the following data:
Table Person
+----+------------+ | Id | Nome | +----+------------+ | 1 | Joãozinho | | 2 | Mariazinha | +----+------------+
Table Person
+----+------------+--------+ | Id | PessoaId | ItemId | +----+------------+--------+ | 1 | 1 | 1 | | 2 | 1 | 2 | | 3 | 2 | 1 | +----+------------+--------+
Item Table
+----+------------+ | Id | Descricao | +----+------------+ | 1 | Item1 | | 2 | Item2 | +----+------------+
One can conclude from this that Joãozinho
owns the Item1
and Item2
, and Mariazinha
has only the Item1
.
By duplicating the data, we would have:
Table Person
+----+------------+ | Id | Nome | +----+------------+ | 1 | Joãozinho | | 2 | Mariazinha | | 3 | Joãozinho | | 4 | Mariazinha | +----+------------+
Table Person
+----+------------+--------+ | Id | PessoaId | ItemId | +----+------------+--------+ | 1 | 1 | 1 | | 2 | 1 | 2 | | 3 | 2 | 1 | | 4 | 3 | 1 | | 5 | 3 | 2 | | 6 | 4 | 1 | +----+------------+--------+
Item Table Remains as before.
To duplicate only 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 am using SQL Server.
You have to duplicate one by one, verify that the ids are valid, disable triggers, in some cases constraints, etc.
– Reginaldo Rigo
I think the most appropriate thing would really be to create a loop within a transaction and do one by one.
– Jedaias Rodrigues
Ok. Even because, in any case, in the frying of the eggs, will be made one by one.
– Reginaldo Rigo
I understand, I’m searching the internet, but I can’t find anything that can help me create this loop to work one by one inside it.
– Jedaias Rodrigues
I’ll post an example.
– Reginaldo Rigo
Why do you want to denormalize your database?
– Giuliana Bezerra
I don’t want to, but the client has my Whatsapp, hahaha...
– Jedaias Rodrigues