Is it Possible to create trigger on system view?

CK 81 Reputation points
2023-03-21T15:18:48.31+00:00

We want to create trigger for master database system view (sys.server_principals). Is it possible?

Basically I want to create a trigger when a login gets created/updated/modified.

Please let me know whether its possible and let me know how to achieve?

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,790 questions
{count} votes

Accepted answer
  1. Erland Sommarskog 111.1K Reputation points MVP
    2023-03-21T21:59:28.68+00:00

    No, you cannot create triggers on system tables.

    However, you can create a server-level DDL trigger for the task. Here is a quick demo:

    CREATE TRIGGER modify_login_tri ON ALL SERVER 
       FOR CREATE_LOGIN, ALTER_LOGIN, DROP_LOGIN AS
       SELECT eventdata()
    go
    CREATE LOGIN testing WITH PASSWORD = 'NotSoSecret'
    ALTER LOGIN testing WITH PASSWORD = 'EvenLessSecret'
    DROP LOGIN testing
    go
    DROP TRIGGER modify_login_tri ON ALL SERVER
    

    The eventdata function gives you details about the command that fired the trigger.


1 additional answer

Sort by: Most helpful
  1. PercyTang-MSFT 12,501 Reputation points Microsoft Vendor
    2023-03-22T02:08:33.66+00:00

    Hi @Karthikeyan Chinnusamy

    You can create triggers on normal views. But creating triggers on system views doesn't seem very realistic.

    You can try the method provided by Erland.

    For more information about DDL triggers, you can refer to this official document.

    https://learn.microsoft.com/zh-cn/sql/t-sql/statements/create-trigger-transact-sql?view=sql-server-ver16

    Best regards,

    Percy Tang

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.