Using MERGE Command in Stored Procedure
MERGE command is introduced in SQL Server 2008. It is a combination of INSERT/UPDATE/DELETE command. Generally it checks if a record is present in the table, if yes then it updates/deletes the record or else it inserts new record. This code snippet is for using the MERGE command in sql stored procedure.
MERGE command is a very useful sql command when we need to perform INSERT/UPDATE/DELETE on a database object based on condition. Instead of writing different code blocks for INSERT/UPDATE/DELETE, we can merge the commands. DotNetSpider has an article regarding MERGE command. Please reffer:
http://www.dotnetspider.com/resources/44872-SQL-SERVER-MERGE-STATEMENT.aspx
But in this code snippet I will show how to use this MERGE command in Stored Procedure. Here it goes:
SET QUOTED_IDENTIFIER ON;
SET ANSI_NULLS ON;
SET NOCOUNT ON;
GO
IF EXISTS (SELECT *
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_NAME = 'SET_REVERT_FLAG'
AND ROUTINE_TYPE = 'PROCEDURE')
BEGIN
PRINT 'Dropping stored procedure SET_REVERT_FLAG.';
DROP PROCEDURE SET_REVERT_FLAG;
END
GO
CREATE PROCEDURE [dbo].[SET_REVERT_FLAG](
@ID bigint,
@IsFlag bit
)
AS
BEGIN
DECLARE @Submit_Flag table (ID bigint, IsFlag bit);
INSERT INTO @Submit_Flag VALUES(@ID,@IsFlag);
MERGE [Submissions_Flag] AS flagTable
USING @Submit_Flag AS sourceTable
ON flagTable.ID = sourceTable.ID
WHEN MATCHED THEN
UPDATE
SET flagTable.IsFlag = @IsFlag,
flagTable.DTS = getdate()
WHEN NOT MATCHED BY TARGET THEN
INSERT (ID, IsFlag, DTS)
VALUES (sourceTable.ID , sourceTable.IsFlag, getdate());
END
GO
---------------------------------------------------------------------------
-- END OF CREATE STATEMENTS.
-- METADATA AND SUCCESS/ERROR MESSAGES BELOW.
---------------------------------------------------------------------------
IF EXISTS (SELECT *
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_NAME = 'SET_REVERT_FLAG'
AND ROUTINE_TYPE = 'PROCEDURE' )
BEGIN
PRINT 'Stored procedure SET_REVERT_FLAG created successfully.';
END
ELSE
BEGIN
PRINT 'ERROR: Failed to create stored procedure SET_REVERT_FLAG.';
END
GO
Hope this code snippet will help developers to implement MERGE command in Stored Procedures.