SQL – How to Update and Select in the same query

The OUTPUT clause Returns information on each row affected by an INSERT, UPDATE, DELETE, or MERGE statement.

These results can be returned to the processing application for further use.

The following example uses the OUTPUT clause to return row values in conjunction with an UPDATE query which effectively enables a SELECT and UPDATE command in the same query.
 
— CREATE TEMP TABLE
CREATE TABLE #TempTable ( URN INT, F1 VARCHAR( 50), F2 VARCHAR(50 ), USED VARCHAR (1))
— INSERT DATA
insert into #TempTable values ( 1,’F1_Val_1′ ,’F2_val_1′, ‘N’)
insert into #TempTable values ( 2,’F1_Val_2′ ,’F2_val_2′, ‘N’)
insert into #TempTable values ( 3,’F1_Val_3′ ,’F2_val_3′, ‘N’)

— UPDATE SINGLE ROW IN TABLE WITH NEW VALUE
— USING OUTPUT COMMAND TO RETURN FIELDS OF UPDATED ROW
UPDATE #TempTable
SET F1 = ‘F1_New_Val’
OUTPUT Inserted.URN, Inserted.F1, Inserted.F2
WHERE URN = 1

— UPDATE MULTIPLE ROWS IN TABLE WITH NEW VALUE
— USING OUTPUT COMMAND TO RETURN FIELDS OF UPDATED ROWS
UPDATE #TempTable
SET F1 = ‘F1_And_F3_new_Val’
OUTPUT Inserted.URN, Inserted.F1, Inserted.F2
WHERE URN in (1 ,3)

— UPDATE ALL ROWS IN TABLE WITH NEW VALUE
— USING OUTPUT COMMAND TO RETURN FIELDS OF ALL ROWS IN TABLE
UPDATE #TempTable
SET F1 = ‘New_Global_Val’
OUTPUT Inserted.URN, Inserted.F1, Inserted.F2

— UPDATE TOP 1 ROW IN TABLE WITH NEW VALUE
— MARK USED = ‘Y’
— USING OUTPUT COMMAND TO RETURN FIELDS OF UPDATED ROW
UPDATE #TempTable
SET F1   = ‘F1_New_Val’
,USED = ‘Y’
OUTPUT Inserted.URN, Inserted.F1, Inserted.F2
WHERE URN in (select max( URN) from #TempTable WHERE used = ‘N’)

— DROP TEMP TABLE
DROP TABLE #TempTable