How to retrieve the input parameter values of a stored procedure

独自空忆成欢 提交于 2019-12-10 00:20:08

问题


I want to create a auditing procedure which will be called in the catch block of all the procedure in my Database.

I wanted to store the list of all the input parameters and its values in this auditing DB.

Please suggest me, how to achieve this in SQL Server


回答1:


I am not aware of programatically retrieving the list of parameters and their values for a stored proc(Possibly would involve n number of system tables and things like that). Without going into that level of complexity AND if altering the current procedures is a possibility, you could do something on the lines of below.

ALTER the existing stored procs to add a small functionality wherein you populate a table variable with
the parameters in a set string format('@paramname = paramvalue') and their values in the current proc and then fire the Auditing proc if the control reaches the CATCH block.

--Add this code bit on top of the proc from where you want the Audit Proc to be fired

--Declare and insert into a table variable
Declare @ParamValues TABLE (params varchar(400))

insert into @ParamValues
select '@id = '+ @id  UNION
select '@name  = '+ @name  UNION
select '@date = '+ @date

GO

...
....
END TRY

begin catch --Auditing proc code below
exec AuditDB.dbo.AuditProc @ParamValues, 
     OBJECT_NAME(@@PROCID) --this returns the name of current proc 
end catch

-------
-------Create the requisite SQL objects
-------
CREATE TABLE AuditDB.dbo.AuditTable
(
    AuditMessage varchar(400),
    ProcName varchar(200),
    DateTimeStamp DateTime
);
GO
CREATE TYPE AuditDB.dbo.ParamValuesType AS TABLE
(
    params varchar(400)
);
GO
CREATE PROCEDURE AuditDB.dbo.AuditProc
    @ParamValues dbo.ParamValuesType READONLY
    ,@ProcName varchar(200)
AS

BEGIN --Add whaterver lines of code required, this is just a basic version.
    INSERT INTO AuditDB.dbo.AuditTable      
    SELECT params, @ProcName, cast(getdate() as datetime) FROM @ParamValues
END;


来源:https://stackoverflow.com/questions/28065713/how-to-retrieve-the-input-parameter-values-of-a-stored-procedure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!