I have a merge statement that should update or insert a single record always. I want to remember the ID of that statement in a variable. It looks like this:
DECLARE @int int
MERGE dbo.table AS A
USING (SELECT 'stringtomatch' AS string) AS B ON B.string= A.string
WHEN MATCHED THEN
UPDATE SET somecolumn = 'something'
WHEN NOT MATCHED THEN
INSERT
VALUES ('stringtomatch',
'something')
OUTPUT @int = inserted.ID;
Now this doesen't work because you can't set @int in the output clause this way. I know I could create a temptable and use INTO @temptable in the output. But since I know it's always a single record I want to have the ID in a INT variable. Is this even possible? Or am I forced to use a table variable. I hope I'm just missing a some syntax.
At most, we can specify only two WHEN MATCHED clauses in the MERGE statement. If two WHEN MATCHED clauses are specified, one clause must have an update operation and the other one must use delete operation.
The OUTPUT clause has access to two temporary or in-memory SQL tables, called INSERTED and DELETED tables. These tables are populated when an INSERT/UPDATE/DELETE operation is done on a table. As a result, the OUTPUT clause can provide us the affected records by referencing these tables. So let's see how to do this.
The OUTPUT clause returns the values of each row that was affected by an INSERT, UPDATE or DELETE statements. It even supports with a MERGE statement, which was introduced in SQL Server 2008 version. The result from the OUTPUT clause can be inserted into a separate table during the execution of the query.
No, you have to use a table variable with OUTPUT
However, you can do this...
...
WHEN MATCHED THEN
UPDATE
SET
@int = ID,
somecolumn = 'something'
WHEN NOT MATCHED THEN
INSERT
VALUES ('stringtomatch',
'something');
SET @int = ISNULL(@int, SCOPE_IDENTITY());
The "assign in UPDATE" has been a valid syntax for SQL Server for a long time. See MERGE on MSDN too. Both say this:
...
<set_clause>::=
SET
...
@variable=expression
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With