Setting variable value using merge operator in SQL Server

67 Views Asked by At
Declare  @IsInserted  Bit
Declare  @Date Datetime=Getdate();

MERGE MASTERSUBJECT AS T
USING #TEMPSUBJECT AS S 
ON T.ID=S.ID
WHEN NOT MATCHED BY TARGET THEN
INSERT (TITLE,OREDRNO,DTMADD,[STATUS]) 
VALUES(S.TITLE,(select MAX(OREDRNO)+1 from 
MASTERSUBJECT),@DATE,1) 
SET  @IsInserted=1     /* IF the record is inserted*/

In the above code I want to update @IsInserted variable to 1 if the insert is successful.

1

There are 1 best solutions below

0
On

For merge, you don't need a variable here. Just use the OUTPUT clause. It is what it was designed for.

OUTPUT
   $action,
   inserted.*,

Or, an alternative...

DECLARE @IsInserted int
SET @IsInserted= ISNULL(@IsInserted, SCOPE_IDENTITY());