Is it possible for a trigger to find the name of the stored procedure that modified data?

前端 未结 3 567
忘了有多久
忘了有多久 2020-12-31 10:27

There are a few stored procedures that routinely get called by a few different systems to do maintenance on a few tables in our database. Some are automated, some aren\'t.

3条回答
  •  时光取名叫无心
    2020-12-31 11:07

    you can try: CONTEXT_INFO

    here is a CONTEXT_INFO usage example:

    in every procedure doing the insert/delete/update that you want to track, add this:

    DECLARE @string        varchar(128)
           ,@CONTEXT_INFO  varbinary(128)
    SET @string=ISNULL(OBJECT_NAME(@@PROCID),'none')
    SET @CONTEXT_INFO =cast('Procedure='+@string+REPLICATE(' ',128) as varbinary(128))
    SET CONTEXT_INFO @CONTEXT_INFO
    
    --do insert/delete/update that will fire the trigger
    
    SET CONTEXT_INFO 0x0 --clears out the CONTEXT_INFO value
    

    here is the portion of the trigger to retrieve the value:

    DECLARE @string         varchar(128)
           ,@sCONTEXT_INFO  varchar(128)
    SELECT @sCONTEXT_INFO=CAST(CONTEXT_INFO() AS VARCHAR) FROM master.dbo.SYSPROCESSES WHERE SPID=@@SPID
    
    IF LEFT(@sCONTEXT_INFO,9)='Procedure'
    BEGIN
        SET @string=RIGHT(RTRIM(@sCONTEXT_INFO),LEN(RTRIM(@sCONTEXT_INFO))-10)
    END
    ELSE
    BEGIN --optional failure code
        RAISERROR('string was not specified',16,1)
        ROLLBACK TRAN
        RETURN
    END
    
    ..use the @string
    

提交回复
热议问题