Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do people use RaiseError instead of Print in T-SQL

I have tried both the below queries and they perform in same time. But still I have seen RaiseError used in many stored procedures instead of print.

Query 1:

BEGIN
    WAITFOR DELAY '00:00:03.00'

    PRINT 'DELAY 1 HAS ENDED'

    WAITFOR DELAY '00:00:03.00'

    PRINT 'DELAY 2 HAS ENDED'
END

Query 2:

BEGIN
    WAITFOR DELAY '00:00:03.00'

    RAISERROR ('DELAY 1 HAS ENDED', 10,1) WITH NOWAIT

    WAITFOR DELAY '00:00:03.00'

    RAISERROR ('DELAY 2 HAS ENDED', 10,1) WITH NOWAIT

END

Both give the desired output only after 6 seconds (I have checked this in SQL Server 2008 R2)

like image 261
Vaibhav Avatar asked Dec 09 '22 22:12

Vaibhav


1 Answers

The advantage of RAISERROR over PRINT is that you may embed variables values within the message without having to bother with CASTand CONVERT. For instance:

 BEGIN
     DECLARE @m INT = 0

     WAITFOR DELAY '00:00:01.00'
     SET @m += 1;
     RAISERROR ('DELAY %d HAS ENDED', 10, 1, @m)
 
     WAITFOR DELAY '00:00:01.00'     
     SET @m += 1;
     RAISERROR ('DELAY %d HAS ENDED', 10, 1, @m)
 
 END

This will produce same output in both examples above, except it will insert the value of variable into the message. With a PRINT you have to do:

PRINT 'DELAY ' + CONVERT(VARCHAR(5), @m) + ' HAS ENDED'

...which is possible but cumbersome...

like image 193
Philippe Raemy Avatar answered Jan 01 '23 03:01

Philippe Raemy