Best Practices - Stored Procedure Logging

后端 未结 4 1743
后悔当初
后悔当初 2021-02-07 02:25

If you have a long running SP, do you log somehow its actions or just wait for this message?

\"Command(s) completed successfully.\"

4条回答
  •  死守一世寂寞
    2021-02-07 03:00

    I use this procedure

    CREATE PROCEDURE dbo.PrintLog (
        @Msg VARCHAR(2048)
        , @Option VARCHAR(100) = ''
        , @Separator VARCHAR(10) = '-'
        )
    /*
    @Option is a string containing possible values as B,A,D,T
    if you want to print separator before message, include B
    if you want to print separator after message, include A
    if you want to print date, include D
    if you want to print time, include T
    Sample: 'BAD'
    
    The order of characters does not matter. it is not case sensitive
    
    Usage:
        exec dbo.PrintLog 'Timed Log', 'T'
        exec dbo.PrintLog 'Dated Log', 'D'
        exec dbo.PrintLog 'With Separator and Time', 'BT', '><'
        exec dbo.PrintLog 'With Separator and Date', 'BAD', '*'
        exec dbo.PrintLog 'With Separator and DateTime', 'BADT', 'x'
    */
    AS
    BEGIN
        declare @tempStr varchar(100)
        set @tempStr = replicate(@Separator, 50)
        IF charindex('B', upper(@Option)) > 0
            raiserror (@tempStr, 10, 1) with nowait
    
        DECLARE @prompt VARCHAR(max) = ''
    
        IF charindex('D', upper(@Option)) > 0
            SET @prompt = convert(VARCHAR, SysDatetime(), 101) + ' '
    
        IF charindex('T', upper(@Option)) > 0
            SET @prompt = @prompt + convert(VARCHAR, SysDatetime(), 108) + ' '
        SET @prompt = @prompt + @Msg
    
        raiserror (@prompt, 10, 1) with nowait
    
        set @tempStr = replicate(@Separator, 50)
        IF charindex('A', upper(@Option)) > 0
            raiserror (@tempStr, 10, 1) with nowait
    
        RETURN
    END
    
    GO
    

    Usage

        exec dbo.PrintLog 'Date and Timed Log', 'DT'
        exec dbo.PrintLog 'Dated Log', 'D'
        exec dbo.PrintLog 'With Separator and Time', 'BT', '><'
        exec dbo.PrintLog 'With Separator and Date', 'BAD', '*'
        exec dbo.PrintLog 'With Separator and DateTime', 'BADT', 'x'
    

    You also can change the parameter defaults to you desired values.

提交回复
热议问题