Latest Entries »

Tuesday, September 27, 2011

Insert Update row with MERGE keyword SQL 2008

Few days ago I've got question how to perform insert/update taks in one query. I couldn't answer because I've never used MERGE in SQL 2008 Server. With my curiosity I make reaserch and google and found a solution. Furthermore almost all examples about MERGE was connected with two tables joining by PK-FK but I needed MERGE with one table. For show this query let first prepare a simple table:
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