My Technical Notes

Wednesday, 2 July 2014

Printing Log Messages with Time in SQL Server

Within stored procedures, PRINT statements appear at the very end when the stored procedure has fully executed. This makes it an unlikely candidate for printing out messages of far the stored procedure has progressed - what we'd rather want is immediate printing of the message.

To this end, I wrote a little stored procedure LogMessage that takes a 'string' as an argument and then prints this together with the time:


CRATE PROCEDURE dbo.LogMessage
 @arg nvarchar(100)
AS
BEGIN
 DECLARE @msg NVARCHAR(MAX) = @arg + '    Time: ' + CONVERT(NVARCHAR(MAX), GETDATE(), 8);
 RAISERROR(@msg, 0, 1) WITH NOWAIT
END
To use it:

EXEC LogMessage 'Hello World'
which prints:

Hello World    Time: 10:13:27

No comments: