[英]Dynamically get all parameter values in stored procedure
Is there any way to get all parameter values from a stored procedure dynamically? 有没有办法动态地从存储过程中获取所有参数值?
In other words, iterate through all parameters in one stored procedure to get their values into one string. 换句话说,在一个存储过程中遍历所有参数,以将它们的值放入一个字符串中。 This is for a unified logging process for a bunch of stored procedures. 这是用于一堆存储过程的统一日志记录过程。
I can get the names of parameters: 我可以得到参数的名称:
SELECT PARAMETER_NAME
FROM INFORMATION_SCHEMA.PARAMETER
WHERE SPECIFIC_NAME = 'procedure_name';
Also, I tried to use dynamic SQL commands. 另外,我尝试使用动态SQL命令。 I've generated a command with included parameter, but EXEC can't execute command. 我生成了包含参数的命令,但是EXEC无法执行命令。
@cmd = 'SELECT '@UserID' + CONVERT(NVARCHAR(MAX), @UserID)
+ '@Date' + CONVERT(NVARCHAR(MAX), @Date)'
EXEC @cmd
Is there any way to do this besides manually generating a list of parameter values for each stored procedure? 除了手动为每个存储过程生成参数值列表之外,还有什么方法可以这样做?
Since SQL Server 2014 there is sys.dm_exec_input_buffer
a table valued function with an output column event_info
that gives the full execution statement (including parameters). 从SQL Server 2014开始, sys.dm_exec_input_buffer
是一个表值函数,其输出列event_info
提供完整的执行语句(包括参数)。
I use this for error logging in stored procedures. 我用它来记录存储过程中的错误。
For example: 例如:
--include this inside the stored procedure
declare @statement nvarchar(max)
select @statement = event_info
from sys.dm_exec_input_buffer(@@spid, current_request_id())
--this will print whatever you called the procedure with (including parameters)
print @statement
-- if you want to parse just the parameters from the statement, it can be done like this
declare @proc_name varchar(128) = object_name(@@procid)
declare @param_idx int = charindex(@proc_name, @statement) + len(@proc_name)
declare @param_len int = len(@statement) - @param_idx
declare @params nvarchar(max) = right(@statement, @param_len)
select @params
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.