Who changed that procedure?!!

Lately, I’ve been doing a lot with Fabric. But every now and then, a very interesting SQL question comes along.

The one I got today was about keeping track of changes in Stored Procedures.

A Stored Procedure?

If you’re new to SQL Server (Welcome, we have cookies!), a stored procedure is essentially a SQL query that is saved in the database. The code can range from very simple (like my example) to very complicated when running ETL processes. Mostly, they’re used to integrate applications with the database, making it easier for app developers to store or retrieve data.

What’s the question?

The question was quite simple: how to track if a procedure has changed. One user creates a procedure; someone else comes in and changes the procedure. In this case, there needs to be some sort of notification.

The answer was a little less simple, or at least less intuitive.

My first thought was to use a trigger on the system view sys.sql_modules. This view exposes the query text and modification date, for example. Instead of running a daily query to see which ones were modified, you may want to be notified, or store the changes somewhere else.

Even though the idea may sound good, it doesn’t work because views don’t support triggers. A view doesn’t contain any data; it’s a stored query that you can select data from.

Building the solution

To ensure I have a secure testing environment, I created a simple stored procedure. It doesn’t really matter what it does, only that it is a valid piece of code.

The procedure

CREATE OR ALTER PROCEDURE usp_TriggerTest AS
BEGIN
	SELECT 1
END;
GO

All this does is store valid code in the database. And return a 1 when run.

To check some basic information stored in the database, you can run the following query.

The stored data

SELECT sql_modules.object_id,
       definition,
       name,
       objects.object_id,
       schema_id,
       type_desc,
       create_date,
       modify_date
FROM sys.sql_modules
INNER JOIN sys.objects ON sys.sql_modules.object_id = sys.objects.object_id;
GO

In my case, this returned the following

Your results will be different

More columns are available should you need them.

The trigger

The main part in this code is the EVENTDATA() function. This will return data on what happened then.
The second is that this isn’t a table-scoped trigger, but a database-level scoped trigger.

Let’s see that in action.

CREATE OR ALTER TRIGGER ddl_test_procedure_change
ON DATABASE
FOR ALTER_PROCEDURE
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @event xml = EVENTDATA();

This is the beginning of the code. Line 2 ensures that the trigger is on the database level.
Line 3 confines the trigger to the database level instead of a table, for instance.

Nocount prevents the output from printing the “number of rows affected” message.

Next, @event is a variable declared as an XML data type that will hold the EVENTDATA() return value.

I need a few extra variables to hold more output details.

    DECLARE @SqlText NVARCHAR(MAX);
    DECLARE @event_object_name sysname 
    DECLARE @UserName sysname;

I’m using the @SqlText to return the full text of the stored procedure.
The @event_object_name variable will hold the name of the stored procedure, and @UserName will point to who ran the statement to change the procedure.

So let’s get some data from event.

    BEGIN
        SET @event_object_name = @event.value('(/EVENT_INSTANCE/ObjectName)[1]', 'sysname');

Remember, @event is the variable that holds the XML returned by the EVENTDATA() procedure. Now I can move through the XML and get the values I want. In this case, I’m going for the object name (the name of the stored procedure.

It is quite interesting to see what’s available. Here’s the full XML.

<EVENT_INSTANCE>
 <EventType>ALTER_PROCEDURE</EventType>
 <PostTime>2026-12-01T20:22:01.277</PostTime>
 <SPID>84</SPID>
 <ServerName>MyServer\SQL2025</ServerName>
 <LoginName>Domain\Reitse.ESKENS</LoginName>
 <UserName>dbo</UserName>
 <DatabaseName>DEMODB</DatabaseName>
 <SchemaName>dbo</SchemaName>
 <ObjectName>usp_TriggerTest</ObjectName>
 <ObjectType>PROCEDURE</ObjectType>
 <TSQLCommand><SetOptions ANSI_NULLS="ON" ANSI_NULL_DEFAULT="ON" ANSI_PADDING="ON" QUOTED_IDENTIFIER="ON" ENCRYPTED="FALSE"/>
 <CommandText>CREATE OR ALTER PROCEDURE usp_TriggerTest AS&#x0D;
BEGIN&#x0D;
	SELECT 1&#x0D;
END;&#x0D;
 </CommandText>
 </TSQLCommand>
</EVENT_INSTANCE>

It’s always fun to see what’s on offer, and it might come in use later.

But, I digress. Let’s set some of the other variables to build the output

        SET @UserName = @event.value('(/EVENT_INSTANCE/LoginName)[1]', 'sysname');
        SET @SqlText = (SELECT definition FROM sys.sql_modules WHERE object_id = OBJECT_ID(@event_object_name));

In the code above, I’m retrieving the login name to see who ran the code. Incidentally, this is also a reason you want to use named accounts for people who log in, not shared accounts like ‘support’, or, the worst, ‘sa’.

The other variable picks the definition from the sys.sql_modules view. I could have used the command text too, but I wanted to show you how you can link to other tables.

Results!

My first test always uses PRINT commands, just to see what comes back.

        PRINT CONCAT_WS(' ', @event_object_name, ' has been updated by', @UserName);
        PRINT 'The new text:'
        PRINT @sqlText

These are simple print statements that return the following when the procedure is changed:

Don’t know who that is

This is cool and shows the main premise works, but if you’re not the one triggering it, you won’t see this. Let’s see if we can save this.

Saving the trigger response

One option is to store this information in the SQL Server log file.

        RAISERROR('The procedure %s has been updated by %s. The new text is: %s', 10, 1, @event_object_name, @UserName, @SqlText) WITH LOG;

By using RAISERROR, I can create my own error message. The %s you see in the regular text references the variables declared at the end. You need the WITH LOG option to actually write this to the log file.

Message. Logged.

And there you have it, a way to store changes to stored procedures. But, are there other ways to do this?

What about Extended Events?

Good question! And it turns out, you can do that too.
You have to remember to make sure this extended events session is started when the server starts. Or restarts. Else you will miss changes.

CREATE EVENT SESSION [GetSPChanges]
ON SERVER
    ADD EVENT sqlserver.object_altered
    (ACTION
     (
         sqlserver.client_hostname,
         sqlserver.database_id,
         sqlserver.database_name,
         sqlserver.sql_text,
         sqlserver.username
     )
     WHERE ([object_type] = (8272))
    )
WITH
(
    MAX_MEMORY = 4096KB,
    EVENT_RETENTION_MODE = ALLOW_SINGLE_EVENT_LOSS,
    MAX_DISPATCH_LATENCY = 30 SECONDS,
    MAX_EVENT_SIZE = 0KB,
    MEMORY_PARTITION_MODE = NONE,
    TRACK_CAUSALITY = OFF,
    STARTUP_STATE = OFF
);
GO

This code checks at the server level for changes to procedures in this database. In this specific code, the data isn’t stored. So change this to how you want to work with it. It also doesn’t start by default.

The WHERE clause filters on the PROC type, which is short for stored procedure.

The output looks like this:

Here you can see the same information.

So, what to do?

I’ve given you two options, which means you now have a choice. Much depends on permissions, the way you want to work, maybe automation that’s reading from the error log. Maybe you want to send an email instead of logging the change in the error log. Maybe you just want to audit who changes procedures. All in all, it really depends on your goal before you make your choice.

I hope this helps you in comparing options.

The full trigger code

I know you like to copy-paste code and see what it does. Well, here you go. Make sure to not run this as-is on production! Even though it should be (mostly) harmless, check and verify!

CREATE OR ALTER TRIGGER ddl_test_procedure_change
ON DATABASE
FOR ALTER_PROCEDURE
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @event XML = EVENTDATA();
    DECLARE @SqlText NVARCHAR(MAX);
    DECLARE @event_object_name sysname;
    DECLARE @UserName sysname;
    BEGIN
        SET @event_object_name = @event.value('(/EVENT_INSTANCE/ObjectName)[1]', 'sysname');
        SET @UserName = @event.value('(/EVENT_INSTANCE/LoginName)[1]', 'sysname');
        SET @SqlText =
        (
            SELECT definition
            FROM sys.sql_modules
            WHERE object_id = OBJECT_ID(@event_object_name)
        );

        PRINT CONCAT_WS(' ', @event_object_name, ' has been updated by', @UserName);
        PRINT 'The new text:';
        PRINT @SqlText;

        RAISERROR(
                     'The procedure %s has been updated by %s. The new text is: %s',
                     10,
                     1,
                     @event_object_name,
                     @UserName,
                     @SqlText
                 ) WITH LOG;
    END;
END;
GO

Leave a Reply