Search code examples
sql-servert-sqlsql-server-2016

Output $action in a INSERT statement


How do I output $action here for "INSERT"?

DECLARE @OutputTbl TABLE (Id int, FirstName nvarchar(50), City nvarchar(50))

INSERT @OutputTbl (Id, FirstName, City)
OUTPUT $ACTION
VALUES
(1,'John','Jackson')

SELECT * FROM @OutputTbl

Msg 207, Level 16, State 1, Line 4 Invalid column name '$ACTION'.

Completion time: 2023-03-29T14:51:33.7353021-04:00


Solution

  • As Dale K has mentioned, and as stated in the documentation, $action is specific to MERGE as a MERGE can INSERT, UPDATE and DELETE.

    $action
    Is available only for the MERGE statement. Specifies a column of type nvarchar(10) in the OUTPUT clause in a MERGE statement that returns one of three values for each row: 'INSERT', 'UPDATE', or 'DELETE', according to the action that was performed on that row.

    On the other hand, an INSERT can only do one thing; INSERT. So, just return that as a literal as you know what the action is:

    DECLARE @OutputTbl TABLE (Id int,
                              FirstName nvarchar(50),
                              City nvarchar(50));
    
    INSERT @OutputTbl (Id, FirstName, City)
    OUTPUT N'INSERT'
    VALUES (1,'John','Jackson');
    
    SELECT *
    FROM @OutputTbl;