BLOGS BY TOPIC
BLOGS BY AUTHOR
BLOGS BY YEAR
This blog gives the low-down on how to start and use the debugger included in SQL Server Management Studio 2008 R2 and SSMS 2012.
- Debugging SQL stored procedures and queries (this blog)
- Basic debugging of SQL
- Using breakpoints
- Other debugging tools
Posted by Andy Brown on 06 June 2013
You need a minimum screen resolution of about 700 pixels width to see our blogs. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.
Debugging SQL stored procedures and queries
It sounds useful, doesn't it? Being able to step through your queries line by line to see where any error occurs? This blog will show how to debug in copious detail, but be warned ...
Debugging SQL is nowhere near as useful as debugging a VB or C# program, since each INSERT, DELETE, UPDATE or SELECT statement can not be broken down into smaller parts.
Our Example Query
The following modest query will call a stored procedure to add 5 types of owl into a table, then display the results:
-- try deleting table
DROP TABLE tblOwl
PRINT 'Deleted table'
PRINT 'No table to delete'
-- execute stored procedure to create table of owls
-- create an integer variable to hold the number of owls
DECLARE @num int
SET @num = ( SELECT COUNT(*) FROM tblOwl )
-- display this value
'Added ' +
CAST(@num AS varchar(10)) +
-- display owls added
The above SQL calls the following stored procedure (I've put this in so I can show the difference betweeen stepping into and stepping over commands):
CREATE PROC spCreateOwlsTable
-- create new temp table (id column autonumbers rows)
CREATE TABLE tblOwl (
OwlId int PRIMARY KEY IDENTITY(1,1),
-- add 5 types of owl
INSERT INTO tblOwl(OwlName) VALUES ('Tawny')
INSERT INTO tblOwl(OwlName) VALUES ('Barn')
INSERT INTO tblOwl(OwlName) VALUES ('African fish')
INSERT INTO tblOwl(OwlName) VALUES ('Long-eared')
INSERT INTO tblOwl(OwlName) VALUES ('Wise')
Running the first query should give the following output:
The query shows the number of owls added, then lists them in a table.
So much for our example - time to begin debugging!
This blog assumes that you're using SQL Server 2008 R2 or SQL Server 2012 - the rules are different for earlier versions of SQL. The blog also assumes that you're connected to a database on the same computer. If this isn't the case, you may need to configure the debugger - here are separate articles showing how to do this for SQL Server 2012 and SQL Server 2008 R2.