Debug a stored procedure in SQL Server, one statement at a time
SQLTreeo T-SQL Debugger steps through a stored procedure one statement at a time. A worked example, and how it compares with PRINT statements and Visual Studio.
SQLTreeo T-SQL Debugger steps through a stored procedure one statement at a time, on SQL Server and on Azure SQL Database. This article finds a wrong result in a small example that way, and then compares it with the other ways to debug a procedure: PRINT statements and Visual Studio.
The example: a total that is too low
Run this in a test database. dbo.OrderTotal should add up the three lines of order 1, which are 2 × 10.00, 1 × 5.00 and 3 × 2.50, so 32.50.
CREATE TABLE dbo.OrderLine (
OrderId int NOT NULL,
LineId int NOT NULL,
Qty int NOT NULL,
Price decimal(10,2) NOT NULL,
PRIMARY KEY (OrderId, LineId)
);
INSERT dbo.OrderLine VALUES (1, 1, 2, 10.00), (1, 2, 1, 5.00), (1, 3, 3, 2.50);
GO
CREATE OR ALTER PROCEDURE dbo.OrderTotal @OrderId int, @Total decimal(12,2) OUTPUT
AS
BEGIN
DECLARE @LineId int = 1;
SET @Total = 0;
WHILE 1 = 1
BEGIN
SELECT TOP (1) @LineId = LineId
FROM dbo.OrderLine
WHERE OrderId = @OrderId AND LineId > @LineId
ORDER BY LineId;
IF @@ROWCOUNT = 0 BREAK;
SET @Total += (SELECT Qty * Price FROM dbo.OrderLine WHERE OrderId = @OrderId AND LineId = @LineId);
END
END
GO
DECLARE @t decimal(12,2);
EXEC dbo.OrderTotal @OrderId = 1, @Total = @t OUTPUT;
SELECT @t AS total;
The result is 12.50, not 32.50. Nothing fails and nothing is printed. You have to find out which line is skipped.
Find the bug with SQLTreeo T-SQL Debugger
SQLTreeo T-SQL Debugger is a Windows application. It runs the procedure on a normal connection, and nothing is installed on the server. To find the bug in the example:
- Connect to the server, find
dbo.OrderTotalin the Object Explorer on the left and double-click it. The code opens in a tab, and a call for it is written in the Batch tab. - In the Batch tab, fill in the call:
EXEC dbo.OrderTotal @OrderId = 1, @Total = @t OUTPUT;, preceded byDECLARE @t decimal(12,2);. - Press Into (F11) to stop at the first statement. The yellow arrow shows the next statement to run.
- Keep pressing Into (F11), or Over (F10) when you do not want to enter a procedure. After the
SELECT TOP (1)has run, the Variables pane shows@LineId = 2. A value that changed since the previous stop is shown in red. - Step on for one more round. After the second pass
@Totalis 12.50, and the nextSELECTfinds no row, so@@ROWCOUNTis 0 and the loop ends.
Line 1 was never visited: the loop looks for a LineId greater than the starting value 1, so the first line is skipped. The declaration should start at 0.
You can speed this up. Press F9 on the SET @Total += line to set a breakpoint and run with Continue (F5): the run stops there on every pass. Add @Total to the Watches to keep it in view. Give the breakpoint a condition in the Breakpoints tab, such as @LineId = 3, to stop only on the third line.
To check the fix, change 1 to 0 in the declaration. You can run CREATE OR ALTER PROCEDURE in your usual query window, or edit the procedure’s tab while the debugger is paused, press Apply and then Save, which ALTERs the procedure in the database. Run the call again: the total is 32.50.
What else it can do that PRINT cannot
- Change a variable while paused. Click the value in the Variables pane, type a new one and press Enter, to see what the rest of the procedure does with it.
- Query the paused connection. The query window runs T-SQL in the procedure you are paused in. It sees the procedure’s variables, its table variables, its temporary tables and the changes of the open transaction that are not yet committed.
- Step into other procedures. Into follows a call to another stored procedure or a scalar function. The Call stack lists the procedures in the chain.
- Pause on an error. See Pause on an error, fix it and retry and Find the statement that fails in a stored procedure.
Other ways to debug a procedure
SQL Server Management Studio 18 and later has no Transact-SQL debugger, so these are the other ways.
PRINT statements
The oldest way: add a PRINT or a RAISERROR ... WITH NOWAIT inside the loop, run the procedure again and read the Messages tab.
PRINT CONCAT('line ', @LineId, ', total so far ', @Total);
It works on every version and every platform, and it costs nothing. The price is that you edit the procedure to look at it, you only see what you thought to print, and every new question means another edit and another run. Here the messages show that the loop starts at line 2, which is enough, but a procedure of three hundred lines that calls two others needs many more PRINT lines, and you have to remove them again afterwards.
Visual Studio
Visual Studio has its own T-SQL debugger. If you already use it, that is a way to step through a procedure. If you do not, it means installing Visual Studio next to SSMS for this one job.
What to know before you start
- It runs your procedure for real. A debug session executes the statements on the connection you chose, so a procedure that inserts rows really inserts them. Use a test database when you are not sure what a procedure changes. Stop (Shift+F5) ends the run and rolls back a transaction it has open.
- Some code runs but cannot be stepped into: dynamic SQL,
INSERT ... EXEC, triggers and multi-statement table-valued functions. Procedures whose definition your login cannot read, such as encrypted procedures or a login withoutVIEW DEFINITION, are greyed out in the Object Explorer. - Rights: the statements run on your connection with your own rights. The debugger steps through the statements of called procedures itself, so ownership chaining does not apply.
- It works on SQL Server and on Azure SQL Database. See Debug a stored procedure on Azure SQL Database.
Next steps
- Download SQLTreeo T-SQL Debugger. The 30-day trial starts at the first start and has every feature.
- Getting started shows connecting and picking a procedure.
- Breakpoints and watches goes through conditions and the watch expressions.