-2

Can you help me create a Query to Insert into Table1 Then update Table2 using inserted Identity?

As with the title, but I need it in SQL Server. I need only to do it once so I want to do this without using triggers. I only found how to do it in PostGres, but I need it in TSQL. I don't know PostGres SQL but I used what I found to create the query below, which is supposed to be in PostGres, but I need it in SQL Server.

    WITH ins  AS (
    INSERT INTO [dbo].[tbl1]
       ([Col1]
       ,[Col2])
       SELECT 
           [Col1]
          ,[Col2]
      FROM [dbo].[Tbl2]
      where ([Tbl2].[Tbl1Id] = 0 OR [Tbl2].[Tbl1Id] is null)
      GROUP BY [Col1], [Col2]
      RETURNING Tbl1Id, Col1, Col2
    )
    UPDATE [Tbl2]
    SET [Tbl2].[Tbl1Id] = ins.[Tbl1Id]
    WHERE [Tbl2].[Col1] = ins.[Col1]
        AND [Tbl2].[Col2]= ins.[Col2] 
Ray Lionfang
  • 689
  • 6
  • 17

1 Answers1

3

There's no returning keyword after the insertion or update, instead of it you can use the OUTPUT keyword, another point is you can't insert/update inside of CTE.

You can first create a temporal/variable table and then when inserting it into tbl1 export the output of the statement into the temporal/variable table(https://stackoverflow.com/a/6292193/4818540) and then use that temporal/variable table for updating your second table.

begin

DECLARE @InsertedIds TABLE (
    Tbl1Id INT,
    Col1   VARCHAR(50),
    Col2   VARCHAR(50)
);

INSERT INTO dbo.tbl1 (Col1, Col2)
OUTPUT inserted.Tbl1Id, inserted.Col1, inserted.Col2 INTO @InsertedIds
SELECT Col1, Col2
FROM dbo.Tbl2
WHERE (Tbl2.Tbl1Id = 0 OR Tbl2.Tbl1Id IS NULL)
GROUP BY Col1, Col2;

UPDATE T2
SET T2.Tbl1Id = I.Tbl1Id
FROM dbo.Tbl2 T2
JOIN @InsertedIds I ON T2.Col1 = I.Col1 AND T2.Col2 = I.Col2;

end;
Farshid Shekari
  • 2,391
  • 4
  • 27
  • 47