CREATE TABLE [dbo].[Target]( [EmployeeID] [int] IDENTITY(1,1) NOT NULL, [EmployeeName] [nvarchar](500) NOT NULL, CONSTRAINT [PK_Target] PRIMARY KEY CLUSTERED ( [EmployeeID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO
Now It's time for write stored procedure that takes adventage of MERGE.
ALTER PROCEDURE [dbo].[TargetInsertUpdate] ( @EmployeeID INT, @EmployeeName NVARCHAR(500), @NewEmployeeID int OUTPUT ) AS SET NOCOUNT ON MERGE dbo.[Target] T -- To check if row is in database we put -- existing row data inside USING (Source table )(S) -- if row exists then name is updated -- otherwise new row is added -- and @NewEmployeeID indicates newly added ID USING (SELECT @EmployeeID as EmployeeID,@EmployeeName as EmployeeName) as S ON T.EmployeeID = S.EmployeeID WHEN NOT MATCHED BY TARGET THEN INSERT(EmployeeName) VALUES(S.EmployeeName) WHEN MATCHED THEN UPDATE SET T.EmployeeName = S.EmployeeName; SET @NewEmployeeID = scope_identity() GO