Skip to content

Instantly share code, notes, and snippets.

@davidsheardown
Created November 19, 2017 20:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidsheardown/82eee8ffc564a9c7eb57d41be907de73 to your computer and use it in GitHub Desktop.
Save davidsheardown/82eee8ffc564a9c7eb57d41be907de73 to your computer and use it in GitHub Desktop.
MS SQL Update AND Insert using MERGE Example
-- Using MS SQL 2008 and above..
-- Create a test table first
CREATE TABLE dbo.DataType
(
ID int IDENTITY(1,1),
TypeName nvarchar(255),
[TypeProperty] nvarchar(255),
CONSTRAINT PK_DataType PRIMARY KEY (ID)
);
INSERT dbo.DataType(TypeName, [TypeProperty]) VALUES (N'name 1', N'property 1');
GO
-- The stored procedure
CREATE PROCEDURE dbo.MergeDataType
@ID int = NULL,
@TypeName nvarchar(255),
@TypeProperty nvarchar(255)
AS
BEGIN
SET NOCOUNT ON;
WITH [source](ID, TypeName, [TypeProperty]) AS
(
SELECT @ID, @TypeName, @TypeProperty
)
MERGE dbo.DataType WITH (HOLDLOCK) AS [target]
USING [source] ON [target].ID = [source].ID
WHEN MATCHED THEN
UPDATE SET [target].TypeName = @TypeName,
[target].[TypeProperty] = @TypeProperty
WHEN NOT MATCHED THEN
INSERT (TypeName, [TypeProperty])
VALUES (@TypeName, @TypeProperty);
END
GO
-- Tests
EXEC dbo.MergeDataType
@TypeName = N'foo',
@TypeProperty = N'bar';
EXEC dbo.MergeDataType
@ID = 1,
@TypeName = N'name 1',
@TypeProperty = N'new property';
GO
SELECT ID, TypeName, [TypeProperty] FROM dbo.DataType;
GO
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment