0

How do i populate the column colNEW in table #tt with the value from column col5 table @t2 in my INSERT statement ? Can my current expression be reused, or do i have to use merge ?

I am using mssql server 10.

DECLARE @t1 TABLE (id INT IDENTITY(1,1), col1 INT, col2 INT)
DECLARE @t2 TABLE (col3 INT, col4 INT, col5 INT)

INSERT @t2 VALUES (1,2,3);INSERT @t2 VALUES (2,3,4)

CREATE TABLE #tt (id INT, col3 INT, col4 INT, colNEW int)

INSERT #tt (id, col3, col4)
SELECT *
FROM
  ( 
INSERT INTO @t1(col1,col2)  
OUTPUT Inserted.id, Inserted.col1,Inserted.col2
SELECT col3, col4  
FROM @t2 
  ) t

I hope someone can help.

t-clausen.dk
  • 43,517
  • 12
  • 59
  • 92

1 Answers1

2

You'll have to use merge:

DECLARE @t1 TABLE (id INT IDENTITY(1,1), col1 INT, col2 INT)
DECLARE @t2 TABLE (col3 INT, col4 INT, col5 INT)

INSERT @t2 VALUES (1,2,3);INSERT @t2 VALUES (2,3,4)

CREATE TABLE #tt (id INT, col3 INT, col4 INT, colNEW int)

INSERT #tt (id, col3, col4,colNew)
SELECT *
FROM
  ( 
MERGE INTO @t1 t1
using @t2 t2 on 1=0
when not matched then INSERT (col1,col2)  
VALUES(t2.col3, t2.col4  )
OUTPUT Inserted.id, Inserted.col1,Inserted.col2,t2.col5
  ) t

select * from #tt

This is a slight misuse of MERGE - I'm only using it because it allows other tables to be referenced in the OUTPUT clause - rather than (for insert) just the inserted table.

Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448