Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Debug output in T-SQL

Tags:

tsql

debugging

When debugging T-SQL, is there something like Javascript's alert(); function or console.log I can use to output values when testing and debugging SQL scripts or stored procedures?

like image 431
silentAmbassador Avatar asked Nov 13 '11 00:11

silentAmbassador


People also ask

What is a debug output?

Debug Output is an OpenGL feature that makes debugging and optimizing OpenGL applications easier. Briefly, this feature provides a method for the driver to provide textual message information back to the application.

How do I debug in SQL?

To debug a function, open the procedure calling that function and insert a breakpoint for the function you want to debug. Then, start debugging. Step through the code using the F11 key or Step Into, or press CTRL+F5 to move directly to the breakpoint. Press F11 or click Step Into to get inside the stored function.

Can we debug SQL query?

Luckily, SQL Server Management Studio (SSMS) comes with automated debugging capabilities to help developers debug their scripts. In this article, we will explain practically how SSMS can be used to debug stored procedures in SQL Server by working through a very simple example.


2 Answers

You can use PRINT to output messages to log but I personally prefer using RAISERROR with low severity because PRINT output is not always printed to screen immediately. Especially in long runnig SP's. On the other hand something like this prints immediately:

RAISERROR ('My Message', 10, 1)

Do not be fooled by the name ERROR, an error with severity 10 does no harm.

As for CTE, I think you are having a problem with self referencing Common Table Expressions. But you should know that there is no way to insert a PRINT statement into the execution of a recursive CTE.
To debug those I usually add an extra "Iteration Index" column to the result set that is incremented with each iteration. Also some other columns to help assess the situation. When examined with the rest of the resultset, it usually gives good insight. Something like the IDX col down. Other columns help me examine join conditions to see what was wrong:

WITH x AS (
    SELECT 1 AS IDX, A._ID as ID_A, NULL as ID_B
    FROM MYTABLE A
    WHERE A._ID = 6

    UNION ALL

    SELECT X.IDX + 1, A._ID, B._ID
    FROM MYTABLE B INNER JOIN X ON B._ID = X._ID + 1
    WHERE B._ID < 20

)
SELECT * 
FROM X
like image 65
e-mre Avatar answered Sep 17 '22 13:09

e-mre


Yes, it's called PRINT. See here:

http://msdn.microsoft.com/en-us/library/ms176047.aspx

like image 42
Stuart Golodetz Avatar answered Sep 16 '22 13:09

Stuart Golodetz