简体   繁体   中英

How to copy data in same table with child and MasterID in SQL Server

We have data in a SQL Server table like this:

PID   Name  RefNo       FID
----------------------------
1    ABC      G1
2    XYZ      G1          1 (1 relate to PID=1)
3    DEF      G1          1 (1 relate to PID=1)

To create a copy of above data in the same table for RefNO G2 we have used SQL query

INSERT INTO Table1 
    SELECT ISNULL(Max(PID),0) + 1, Name, 'G2', FID 
    FROM Table1

and it has copied the data like

1    ABC      G1
2    XYZ      G1          1 *(1 relate to PID=1)*
3    DEF      G1          1 *(1 relate to PID=1)*
4    ABC      G2
5    XYZ      G2          1 *(it should be 4 but it is showing 1 by my query)*
6    DEF      G2          1 *(it should be 4 but it is showing 1 by my query)*

Please guide how do I write the correct query to get my desired result as below

1    ABC      G1
2    XYZ      G1          1 
3    DEF      G1          1 
4    ABC      G2
5    XYZ      G2          4 
6    DEF      G2          4 

Create temporary table and insert data into it. below query help you do this.

create table #Temp
(
    PID int ,
    Name VARCHAR(100), 
    RefNo Varchar(50), 
    FID int 
)
INSERT INTO #Temp
SELECT * FROM temp1

Below Code help to insert data into main table using Cursor.

DECLARE @Name VARCHAR(50),
        @FID INT,@TFID INT = NULL, 
        @RefNo VARCHAR(10) = 'G2' 
DECLARE cur CURSOR
FOR 
    SELECT Name ,FID
    FROM #Temp

OPEN cur
FETCH NEXT FROM cur INTO @Name,@FID
WHILE @@FETCH_STATUS = 0
BEGIN       
    IF @FID IS NULL
    BEGIN
        SELECT @TFID = NULL
    END
    INSERT INTO temp1(Name,RefNo,FID)
    VALUES ( @Name, @RefNo, @TFID)
    
    IF @FID  IS NULL
    BEGIN
        SELECT @TFID = @@IDENTITY
    END
    FETCH NEXT FROM cur INTO @Name,@FID
END
CLOSE cur
DEALLOCATE cur

After insert please delete #tTemp Table

drop table #Temp

You get updated main table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM