Consider the following stored procedure..
CREATE PROCEDURE SlowCleanUp (@MaxDate DATETIME)
AS
BEGIN
PRINT 'Deleting old data Part 1/3...'
DELETE FROM HugeTable1 where SaveDate < @MaxDate
PRINT 'Deleting old data Part 2/3...'
DELETE FROM HugeTable2 where SaveDate < @MaxDate
PRINT 'Deleting old data Part 3/3...'
DELETE FROM HugeTable3 where SaveDate < @MaxDate
PRINT 'Deleting old data COMPLETED.'
END
Let's say that each delete statement take a long time to delete, but I like to see the progress of this stored procedure when I'm running it in SQL Management Studio. In other words, I like to see the the output of the PRINT statements to see where I'm at any given time. However, it seems that I can only see the PRINT outputs at the end of the ENTIRE run. Is there a way to make it so that I can see the PRINT outputs at real time? If not, is there any other way I can see the progress of a running stored procedure?
If you use RAISERROR
with a severity of 10 or less, and use the NOWAIT
option, it will send an informational message to the client immediately:
RAISERROR ('Deleting old data Part 1/3' , 0, 1) WITH NOWAIT
Yes you should be able to get the message to print immediately if you use RAISERROR:
RAISERROR('Hello',10,1) WITH NOWAIT
I have found a great NON-INTRUSIVE way to see the progress of along running stored procedure. Using code I found on Stackoverflow of SP_WHO2, you can see the first column has the current code actually being run from the PROC. Each time you re-run this SP_Who2 process, it will display the code running at the time.This will let u know how far along your proc is at anytime. Here is the sp_who2 code which I modified to make it easier to track progress:
Declare @loginame sysname = null
DECLARE @whotbl TABLE
(
SPID INT NULL
,Status VARCHAR(50) NULL
,Login SYSNAME NULL
,HostName SYSNAME NULL
,BlkBy VARCHAR(5) NULL
,DBName SYSNAME NULL
,Command VARCHAR(1000) NULL
,CPUTime INT NULL
,DiskIO INT NULL
,LastBatch VARCHAR(50) NULL
,ProgramName VARCHAR(200) NULL
,SPID2 INT NULL
,RequestID INT NULL
)
INSERT INTO @whotbl
EXEC sp_who2 @loginame = @loginame
SELECT CommandText = sql.text ,
W.*
,ExecutionPlan = pln.query_plan
,ObjectName = so.name
,der.percent_complete
,der.estimated_completion_time
--,CommandType =der.command
FROM @whotbl W
LEFT JOIN sys.dm_exec_requests der
ON der.session_id = w.SPID
OUTER APPLY SYS.dm_exec_sql_text (der.sql_handle) Sql
OUTER APPLY sys.dm_exec_query_plan (der.plan_handle) pln
LEFT JOIN sys.objects so
I wish I remember who I got this original code from, but it has been VERY helpful. It also identifies the SPID if I need to kill a process.