I started working on a project that already has some scripts running and while I was looking some of the scripts that have already been done I encountered an scenario that looks something like this.
DROP TABLE IF EXISTS #Persons
SELECT PersonId = 1, Firstname = 'Joaquin', LastName = 'Alvarez'
INTO #Persons
DECLARE @inserted table (PersonId INT, Firstname VARCHAR(50), Lastname VARCHAR(50))
MERGE INTO dbo.Persons P USING #Persons TP ON 1 = 0 -- Forcing mismatch
WHEN NOT MATCHED THEN
INSERT
(
PersonId,
Firstname,
Lastname
)
VALUES
(
TP.PersonId,
TP.Firstname,
TP.LastName
)
OUTPUT INSERTED.PersonId, INSERTED.Firstname, INSERTED.LastName
INTO @inserted;
My Question here is why they would use the merge into and force the mismatch just to perform an insert, they could have done the same without it with something like this.
DROP TABLE IF EXISTS #Persons
SELECT PersonId = 1, Firstname = 'Joaquin', LastName = 'Alvarez'
INTO #Persons
DECLARE @inserted table (PersonId INT, Firstname VARCHAR(50), Lastname VARCHAR(50))
INSERT INTO Persons
OUTPUT INSERTED.PersonId, INSERTED.Firstname, INSERTED.LastName
INTO @inserted
VALUES (1, 'Joaquin', 'Alvarez')
The first option is faster than the last one? or they're bot the same? This is the first time I see the merge into used this way.