Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use OUTPUT clause of SQL Server for update

DECLARE @t2 AS TABLE(id INT)  

INSERT INTO dbo.EntityMaster
        (EntityType)
OUTPUT INSERTED.EntityId INTO @t2
SELECT 'G' FROM #tmp

#tmp is a temporary table that contains data loaded from an xml. I need to generate EntityId for each record contained in #tmp. It can be done by inserting record first into EntityMaster table then insert this entityid back into #tmp for each record.

Instead of inserting record into @t2, I need to update #tmp for each record.

Any possibility?

like image 936
Shantanu Gupta Avatar asked Sep 13 '12 20:09

Shantanu Gupta


People also ask

Can I use from clause in update?

UPDATE statements with a FROM clause are often used to update information in a table based on a table-valued parameter (TVP), or to update columns in a table in an AFTER trigger. For the scenario of update based on a TVP, see Implementing MERGE Functionality in a Natively Compiled Stored Procedure.

What is the use of output clause in SQL Server?

The OUTPUT clause returns columns from the table being deleted ( deleted. ProductID , deleted. ProductPhotoID ) and columns from the Product table. This table is used in the FROM clause to specify the rows to delete.

How do you use an output clause?

Using the OUTPUT clause, we can display the rows inserted into a table in the output window by selecting the column names with the INSERTED prefix or using INSERTED. * to display all the columns. This will also help in printing out some of the output messages on the management studio window for confirmations.

Which clause is used to update the data in SQL?

The UPDATE statement in SQL is used to update the data of an existing table in database. We can update single columns as well as multiple columns using UPDATE statement as per our requirement. UPDATE table_name SET column1 = value1, column2 = value2,...


1 Answers

Try Something like this, you still have to use the temp table but it's not too bad to read and it gets the job done.

CREATE TABLE #tmp
(
    tmpID INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
    xmlData VARCHAR(255),
    EntityId INT
)
DECLARE @t2 TABLE
(
    tmpID INT,
    EntityId INT
)

MERGE dbo.EntityMaster AS EM
USING
(
    SELECT tmpID,
        xmlData,
        EntityId
    FROM #tmp
) AS X
    ON EM.EntityId = X.EntityId
WHEN NOT MATCHED THEN
    INSERT (EntityType)
    VALUES (X.xmlData)
OUTPUT X.tmpID, INSERTED.EntityId
INTO @t2 (tmpID, EntityId);

UPDATE T
SET EntityId = T2.EntityId
FROM @t2 T2
INNER JOIN #tmp T
    ON T2.tmpID = T.tmpID

like image 115
TheZachHill Avatar answered Oct 17 '22 11:10

TheZachHill