The multi-part identifier “” could not be bound. with insert statement to get non insert values into OUTPUT variable in SQL Server

Today, one of my colleague was asking how to get the non inserted values from the insert statement to output table variable.
Here is a sample code that he tried to get information. He reported there is an error message as below.

Msg 4104, Level 16, State 1, Line 12
The multi-part identifier “p.PId” could not be bound.

Sample code:


CREATE TABLE T1 (RID INT IDENTITY(1, 1), col1 INT, col2 INT)
CREATE TABLE T2 (PID INT IDENTITY(1, 1), col1 INT, col2 INT)
Declare @OutputTable Table (ID INT IDENTITY(1, 1), PID INT, RID INT, col1 INT, col2 INT)

INSERT INTO T2 VALUES (1, 1), (2, 2), (3, 3), (4, 4)

INSERT into T1 (col1, col2) 
	OUTPUT p.PId, inserted.RID, inserted.col1, inserted.col2
	INTO @OutputTable (PID, RID, col1, col2)
Select Col1, Col2 From T2 p

SELECT  * FROM    @OutputTable

DROP TABLE T1,T2

Solution:
While analyzing, it is clear that there is no straight way to get non-inserted values into OUTPUT clause.But, there is work around to get the information for this scenario by using MERGE and use the INSERT statement as below:


CREATE TABLE T1 (RID INT IDENTITY(1, 1), col1 INT, col2 INT)
CREATE TABLE T2 (PID INT IDENTITY(1, 1), col1 INT, col2 INT)
Declare @OutputTable Table (ID INT IDENTITY(1, 1), PID INT, RID INT, col1 INT, col2 INT)

INSERT INTO T2 VALUES (1, 1), (2, 2), (3, 3), (4, 4)

MERGE INTO T1 r USING T2 p ON 1 = 0
WHEN NOT MATCHED THEN
    INSERT (col1, col2) VALUES (p.col1, p.col2)
    OUTPUT p.PId, inserted.RID, inserted.col1, inserted.col2
    INTO @OutputTable (PID, RID, col1, col2);

SELECT  * FROM    @OutputTable

DROP TABLE T1,T2

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s