0

For years, to debug stored procedures I use a very lame basic approach. I wonder if there is a more modern way or tool to make life easier.

Let's say we ran the stored procedure

EXECUTE MyCoolProcedure 'Parameter1', 2, 'Parameter3', '2019-11-25'

And it fails with the error

Msg 8134, Level 16, State 1, Procedure MyCoolProcedure, Line 11 [Batch Start Line 0]
Divide by zero error encountered.

This Line 11 part is not particularly helpful because it is not clear how those lines are numbered.

If I click Modify on the stored procedure, I see

USE [MyCoolDatabase]
GO
/****** Object:  StoredProcedure [dbo].[MyCoolProcedure]    Script Date: 11/26/2019 3:01:05 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[MyCoolProcedure]
(
    @p1 varchar(20),
    @p2 int,
    @p3 varchar(30),
    @p4 smalldatetime
)
AS
BEGIN
    SELECT -- I bet it fails in here, Line #18
        1 /
        (@p2 - 2
        );
END;

Here it is obvious it is failing in the line #18, so probably we just need to add 7 to whatever line number is shown. But you see it is like a rule of thumb.

But let's pretend it's not so obvious what is failing in here, so we need to put some debugging statements around to figure out what is wrong

Write now what I do is I copy the whole content of the procedure declaration and edit it in-place


ALTER PROCEDURE [dbo].[MyCoolProcedure] DECLARE
(
    @p1 varchar(20) = 'Parameter1',
    @p2 int = 2,
    @p3 varchar(30) = 'Parameter3',
    @p4 smalldatetime = '2019-11-25'
)
AS
BEGIN
    SELECT -- I bet it fails in here, Line #18
        1 /
        (@p2 - 2
        );
END;

This is a bit time consuming and annoying. Ideally as a Visual Studio user, I would prefer to have something like Attach to process and Break on error functionality.

Am I doing it wrong? Is there a more efficient way to do those repetitive tasks?

5
  • in SSMS rather execute click debug then step into rather over Nov 26, 2019 at 1:22
  • @maSTAShuFu it it's ok for simple cases. But in really you need to more debugging statements around the problematic code to see what causes the problem
    – mnaoumov
    Nov 26, 2019 at 1:37
  • well i guess if you'd like to make it harder for yourself then use sql profiler Nov 26, 2019 at 1:41
  • @maSTAShuFu I don't get it. From the sql profiler I just see that EXECUTE MyCoolProcedure 'Parameter1', 2, 'Parameter3', '2019-11-25' part, which doesn't help with the internals
    – mnaoumov
    Nov 26, 2019 at 2:01
  • There are also events for sp_statement_starting and sp_statement_completed in both Profiler and Extended Events.
    – Dan Guzman
    Nov 26, 2019 at 2:08

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.