How to debug a T-SQL trigger?
You're actually over-thinking this.
I first run this query in one window (to set things up):
create table X(ID int not null)
create table Y(ID int not null)
go
create trigger T_X on X
after insert
as
insert into Y(ID) select inserted.ID
go
I can then discard that window. I open a new query window, write:
insert into X(ID) values (1),(2)
And set a breakpoint on that line. I then start the debugger (Debug
from menu or toolbar or Alt-F5) and wait (for a while, the debugger's never been too quick) for it to hit that breakpoint. And then, having hit there, I choose to Step Into
(F11). And lo (after another little wait) a new window is opened which is my trigger, and the next line of code where the debugger stops is the insert into Y...
line in the trigger. I can now set any further breakpoints I want to within the trigger.
I also wasn't able to Step Into
, it would go straight over my INSTEAD OF INSERT
trigger. So I ended up replacing the trigger with:
ALTER TRIGGER [MyView_Instead_Insert]
ON [MyView]
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON
select * into temp from INSERTED
END
Which created a table called temp with exaclty the column names and values of INSERTED
.
There is a DEBUG menu in SSMS, but you'll likely need to be on the server to be able to debug, so if it is a remote access, it's probably not gonna be set up for it. That debug option will allow you to execute code, and step into your trigger and debug it in that manner (as you'd debug most any other code).
If not having access to the debug menu/function, you'll have to debug "manually":
First ensure your trigger is running correctly by inserting the input of the trigger into a debug table. Then you can verify that its called correctly. Then you can debug the query of the trigger as you would any other sql query, using the values from the debug table.