Suppose we have a self-charging table like this
CREATE TABLE Month
(
Id int IDENTITY(1,1) PRIMARY KEY,
Title char(128)
)
CREATE TABLE Entity
(
Id int IDENTITY(1,1) PRIMARY KEY,
MonthId int FOREIGN KEY REFERENCES Month(Id),
Name char(128),
ParentId int FOREIGN KEY REFERENCES Entity(Id),
)
I want to copy all rows of a specific month into another MonthId. You must also update the duplicate parentId, entities and their parents should be in the same month.
as an example, suppose that
Id MonthId Name ParentId
------------------------------------
1 1 name1 null
2 1 name11 1
3 1 name3 null
4 1 name31 3
5 1 name311 4
after copying monthId = 1 rows to monthId = 2, the result should look like this:
Id MonthId Name ParentId
------------------------------------
1 1 name1 null
2 1 name11 1
3 1 name3 null
4 1 name31 3
5 1 name311 4
newId1 2 name1 null
newId2 2 name11 newId1
newId3 2 name3 null
newId4 2 name31 newId3
newId5 2 name311 newId4
newId are the values that are generated by the DBMS.
Note. I use Sql-Server 2012 as a DBMS.
source
share