I am trying to perform the following using a MERGE
statement
I have a table that has two columns (TagId
is an Identity (PK) and Name
as a VARCHAR
). I would like to check first if Name
exists before I insert it. If it does exist, I would like to get the Identity value. Otherwise, I would insert it and pick up the inserted value.
The beauty of MERGE
is it is transactional in nature. so, I won't have to worry about getting an UNIQUE
index violation due to timing. Any suggestions? I prefer not to use transactions.
DECLARE
@TagId INT,
@Name VARCHAR(100) = 'TagName'
SELECT TOP(1)
@TagId = T.TagId
FROM dbo.Tag AS T
WHERE T.Name = @Name
IF @TagId IS NULL
BEGIN
INSERT dbo.Tag (Name) VALUES (@Name)
SELECT @TagId = SCOPE_IDENTITY()
END
After trying, this seems to work: it doesn't seem right. The MATCHED
clause is required. Otherwise, @Table
won't have value.
DECLARE @Table TABLE
(
TagId INT,
Name VARCHAR(100)
)
DECLARE
@TagId INT,
@Name VARCHAR(100) = 'TdagNamed122'
MERGE dbo.Tag AS Target
USING(SELECT @Name) AS Source (Name)
ON Source.Name = Target.Name
WHEN MATCHED THEN
UPDATE SET @TagId = Target.TagId
WHEN NOT MATCHED THEN
INSERT (Name) VALUES (Source.Name)
OUTPUT INSERTED.* INTO @Table
;
SELECT * FROM @Table