Search code examples
sql-servert-sqldatabase-triggernocount

Trigger with NOCOUNT outputs 1 or more row(s) affected when no datatable rows were changed


I am using SQL Server 2012. I have triggers on a view, with the intent of allowing my users to perform DML actions on it like any other table. These triggers have SET NOCOUNT ON and have many IF...RAISERROR(...) RETURN statements to catch logical errors. I noticed that even when a trigger is returned without affecting any underlying tables, SSMS outputs "n or more row(s) affected" where n is the number of rows that would have been affected in the view. So, I tested the following simple trigger, with the same results:

CREATE TRIGGER dbo.triggerViewTest 
ON dbo.viewTest
INSTEAD OF INSERT AS
BEGIN
    SET NOCOUNT ON
    IF 1 != 0
    BEGIN
        RAISERROR('No rows should be affected!', 16, 1)
        RETURN
    END
END

INSERT INTO dbo.viewTest (columnA) VALUES (1)

And SSMS prints 1 row(s) affected.

How do I suppress this output?


Solution

  • Following will prevent this message returned to console. It is related with session settings not with the trigger code

    set nocount on
    insert into viewTest select...
    set nocount off