获取存储过程参数名称和值

时间:2016-10-07 10:12:48

标签: sql-server

我想在所有存储过程中使用相同的catch代码。一切正常,但不知道如何获取所有参数名称和值的列表。

CREATE procedure addNewItem @messageNo integer out,
                            @message nvarchar(4000) out,
                            @companyId smallint,
                            @itemNumber bigint,
                            @itemDescription nvarchar(4000)
as
begin try
    Set @companyId = 'a'  
end try
begin catch
    if ERROR_SEVERITY() = 11
    begin
        Set @message = ERROR_MESSAGE()
        Set @messageNo = ERROR_STATE() * (-1)
    end
    else
    begin
        Set @message = 'Error. Please, contact support.' + CHAR(13) + CHAR(10)
        Set @message = @message + ERROR_MESSAGE() + CHAR(13) + CHAR(10) +
                'PARAMS: ???' + /* get params somehow */ CHAR(13) + CHAR(10) +
                'ERROR_NUMBER: ' + cast(ERROR_NUMBER() as nvarchar) + CHAR(13) + CHAR(10) +
                'ERROR PROCEDURE: ' + ERROR_PROCEDURE () + CHAR(13) + CHAR(10) +
                'ERROR LINE: ' + cast(ERROR_LINE() as nvarchar)
        Set @messageNo = ERROR_NUMBER() * (-1)
    end

end catch

EXEC

-- execution
declare @messageNo integer,
        @message nvarchar(4000)
exec addNewItem @messageNo out, @message out, 1, 1, 'New Item'             
print @message

我想获取所有参数名称,其值与'PARAMS:'一致,但我不知道如何做到这一点。每个过程都有相同的@MesageNo和@message,但所有其他参数的计数,名称和值在每个过程中都可以不同。

我想得到像:

Error. Please, contact support.
Conversion failed when converting the varchar value 'a' to data type smallint.
PARAMS: 'companyId: 1; itemNumber: 1; itemDescription: New Item'
ERROR_NUMBER: 245
ERROR PROCEDURE: addNewItem
ERROR LINE: 8

感谢您的帮助。

我创造了这样的事情:

declare @results varchar(4000)
SELECT @results = coalesce(@results + ' + ', '') + convert(varchar(200), '''; ' + P.name + ': '' + cast(') + convert(varchar(200), P.name) + ' as nvarchar)'
FROM sys.objects AS SO
INNER JOIN sys.parameters AS P 
ON SO.OBJECT_ID = P.OBJECT_ID
WHERE SO.OBJECT_ID IN ( SELECT OBJECT_ID 
FROM sys.objects
WHERE NAME = 'addNewItem') and P.name not in ('@messageNo', '@message')
Set @results = '''' + SUBSTRING(@results, 4, LEN(@results))
print @results

结果是STRING:

'@companyId: ' + cast(@companyId as nvarchar) + '; @itemNumber: ' + cast(@itemNumber as nvarchar) + '; @itemDescription: ' + cast(@itemDescription as nvarchar)

但我不知道如何执行它,当我使用EXECUTE sp_executesql时,我得到一条消息,我必须声明变量:(

0 个答案:

没有答案
相关问题