如何检索存储过程的输入参数值

时间:2015-01-21 11:09:23

标签: tsql sql-server-2012

我想创建一个审核程序,该程序将在我数据库中所有程序的catch块中调用。

我想在此审核DB中存储所有输入参数及其值的列表。

请建议我,如何在SQL Server中实现这一点

1 个答案:

答案 0 :(得分:0)

我不知道以编程方式检索存储过程的参数列表及其值(可能涉及n个系统表和类似的东西)。如果没有达到这种复杂程度,如果有可能改变当前的程序,你可以在下面的行上做点什么。

ALTER现有存储过程添加一个小功能,其中用VB填充表变量 设置字符串格式('@paramname = paramvalue')中的参数及其在当前proc中的值 然后,如果控件到达CATCH块,则触发审计过程。

--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;
相关问题