Need to port data in sql child table
-
05-06-2021 - |
質問
Need to port data in sql table
I have a master table with columns (masterid, masterdata, year
). Here masterid
is an identity column.
I have the data for year 2012. I need to same 2012 data for 2013
I could solve the problem by simply running a SQL statement like:
INSERT INTO mastertable
SELECT masterdata, 2013
FROM mastertable WHERE Year = 2012
I would like to run similar kind of run for child table also.
My child table structure is: (childid , masterid, childdata
)
Here I have child data for the year 2012, I want to have similar data for year 2013 with proper masterid
created for master data for the year 2013 in first step.
Preferably I would like to have solution without adding additional temporary columns
Any lead greatly appreciated.
Regards, Kumar.
解決
You'll need to store the links between the 2013 and 2012 records created in the mastertable
table. If you want to achieve this without adding any additional temporary columns you'll need to use T-SQL.
(I've guessed a type of varchar(max)
for masterdata as you haven't specified its type).
DECLARE @links TABLE ( masterid int, newmasterid int )
DECLARE @mastertemp TABLE ( masterid int, masterdata varchar(max) )
DECLARE @masterid int,
@masterdata varchar(max)
INSERT INTO @mastertemp
SELECT masterid,
masterdata
FROM mastertable
WHERE [year] = 2012
WHILE EXISTS ( SELECT TOP 1 * FROM @mastertemp )
BEGIN
SELECT TOP 1 @masterid = masterid,
@masterdata = masterdata
FROM @mastertemp
INSERT INTO mastertable
VALUES ( @masterdata, 2013 )
INSERT INTO @links
VALUES ( @masterid, SCOPE_IDENTITY() )
DELETE FROM @mastertemp
WHERE masterid = @masterid
END
INSERT INTO childtable
SELECT l.newmasterid,
c.childdata
FROM childtable c
INNER JOIN @links l ON c.masterid = l.masterid
他のヒント
Assume the ChildId
is identity column with auto increment
You can wrap them up in function/stored procedure without need of temporary table.
UPDATED
Declare @Year int
SET @Year = 2011
INSERT INTO MasterTable
SELECT masterdata, 2013
FROM mastertable WHERE Year = @Year
INSERT INTO childtable
SELECT SCOPE_IDENTITY(), c.childdata
FROM childtable c
WHERE masterid in
(
SELECT masterid
FROM masterTable
WHERE Year = @Year
)