1

I have a query running in loop which I am trying to optimize as this

INSERT INTO myTable (col1, col2, col3)
OUTPUT inserted.id, SOURCE_ROW_ID_NEEDED_HERE
    SELECT col1, col2, col3 
    FROM myTable 
    WHERE col2 = 20 --any value

My problem is : col2 = 20 can have N number of rows which get inserted, I need the id of the source row for the new record. For example say there are 3 rows for col2 = 20 and id of them are 11,12,15. The new inserted ID are say 150,151,152.

I would need

11  150
12  151
15  152
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
CFML_Developer
  • 1,565
  • 7
  • 18

1 Answers1

0

Are you looking for something like

CREATE TABLE T1(
  Col1 INT IDENTITY(1, 1),
  Col2 INT,
  Col3 INT
);

CREATE TABLE T2(
  Col1 INT IDENTITY(1, 1),
  Col2 INT,
  Col3 INT
);

INSERT INTO T2(Col2, Col3) VALUES
(11,  150),
(12,  151),
(15,  152);

DECLARE @TT TABLE (ID INT, Col2 INT);

SET IDENTITY_INSERT T1 ON;

INSERT INTO T1 (Col1, Col2, Col3)
OUTPUT INSERTED.Col1,
       INSERTED.Col2
INTO @TT (ID, Col2)
SELECT Col1,
       Col2,
       Col3
FROM T2;

SELECT *
FROM @TT;

SET IDENTITY_INSERT T1 OFF;

Demo

Ilyes
  • 14,640
  • 4
  • 29
  • 55