【问题标题】:SQL Server 2008 Try/Catch parameter names and valuesSQL Server 2008 Try/Catch 参数名称和值
【发布时间】:2011-11-22 17:00:13
【问题描述】:

我已经搜索过,但无法找到如何从 SQL Server 2008 中的 try/catch 的 catch 部分获取存储过程的参数名称和值。

我知道如何获取参数例如:

SELECT  parm.name AS Parameter
        ,typ.name AS [Type]
FROM    sys.procedures sp
        JOIN sys.parameters parm ON sp.object_id = parm.object_id
        JOIN sys.types typ ON parm.system_type_id = typ.system_type_id
WHERE   sp.name = OBJECT_NAME(@@procid)

基本上我正在寻找的是使用参数和值执行的 SP,以便我可以记录和排除故障。比如:

wsp_GetUser_s @UserID = 123, @UserName = 'juser'

【问题讨论】:

  • 也许我遗漏了一些东西,但如果你在谈论 SP 中的 try catch 块,比如 SP1,并且你想记录传递给 SP1 的参数,你怎么会不知道参数名称和值?
  • 如果可能的话,我不想手动编写所有这些代码,最好制作一个动态执行此操作的 sn-p。说添加了一个新参数,我宁愿不更改catch中的代码。此外,在生成 SP 时,最好不必编写所有代码。

标签: sql-server sql-server-2008 stored-procedures try-catch


【解决方案1】:

Microsoft SQL Server 的 catch 块中没有自动记录传入数据库对象的参数的功能。

如果你想知道传入了哪些参数,我建议运行跟踪或使用扩展事件。

如果这些选项都不可行,我建议创建一个表来存储这些信息。一列可以有存储过程名称,另一列可以有参数。参数列可以包含以逗号分隔的列表,其中包含传递到存储过程中的任何参数。

例子:

create table dbo.Parameters ( 
RowID int identity(1,1),
StoredProcedure varchar(255),
Parameters varchar(max)
)

create proc dbo.wsp_GetUser_s  ( 
@UserID int,
@UserName varchar(255)
)
as
begin try
select *
from dbo.Users
where UserID = @UserID
and UserName = @UserName

-- We'll only log to the Parameters table if we don't find a match
if @@rowcount < 1
begin
RAISERROR ('Did not find user. Logging passed parameters to dbo.Parameters table', -- Message text.
               16, -- Severity.
               1 -- State.
               );
end

end try
begin catch
-- This could be moved into the catch block if you wanted to log this for all calls and not only when there is no match found for the passed in parameters.
insert into dbo.Parameters ( StoredProcedure, Parameters)
select 'wsp_GetUser_s', '@UserID=' + @UserID + ', @UserName=' + @UserName
end catch

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多