在存储过程中更改EXEC函数中的参数值

时间:2018-01-12 00:15:39

标签: sql-server stored-procedures

我有一个存储过程,我插入这样的产品:

BEGIN TRY
    -- Insert statements for procedure here
    INSERT INTO Product.ProductDetail VALUES (@ProductId,@IsDeleted);
    return 1;
    COMMIT TRANSACTION
END TRY
BEGIN CATCH
INSERT INTO Exception.SqlTransaction VALUES ('usp_AddProduct', ERROR_NUMBER(), ERROR_SEVERITY(), ERROR_STATE(),  ERROR_PROCEDURE(), ERROR_LINE(),
ERROR_MESSAGE())
    return 0

    ROLLBACK TRANSACTION

如您所见,我在Exception.SqlTransactions中插入了sp和sql错误代码的名称。我想要做的是用该插入创建另一个sp并使用EXEC,如何发送sp的名称?

首先我创建sqlErrorCodes SP:

CREATE PROCEDURE SQLErrorCodes 
    -- Add the parameters for the stored procedure here
    @sp_Name varchar(max) 

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
INSERT INTO Exception.SqlTransaction VALUES (@sp_Name, ERROR_NUMBER(), ERROR_SEVERITY(), ERROR_STATE(),  ERROR_PROCEDURE(), ERROR_LINE(),
ERROR_MESSAGE())
END
GO

然后进入原始sp我改变这一行

INSERT INTO Exception.SqlTransaction VALUES ('usp_AddProduct', ERROR_NUMBER(), ERROR_SEVERITY(), ERROR_STATE(),  ERROR_PROCEDURE(), ERROR_LINE(),
    ERROR_MESSAGE())

现在我用:

EXEC SQLErrorCodes('usp_AddProduct')

但我明白了:

  

'usp_AddProduct'附近的语法不正确。

我做错了什么?当我将EXEC句子用于另一个sp时,如何更改参数值@sp_Name?此致

更新

正如亚历克斯评论我将sp改为:

ALTER PROCEDURE [dbo].[SQLErrorCodes] 
    -- Add the parameters for the stored procedure here
    @sp_Name varchar(max), 
    @ErrorNumber varchar(max) = ERROR_NUMBER,
    @ErrorSeverity varchar(max) = ERROR_SEVERITY,
    @ErrorState varchar (max) = ERROR_STATE,
    @ErrorProcedure varchar (max) = ERROR_PROCEDURE ,
    @ErrorLine varchar(max) = ERROR_LINE,
    @ErrorMessage varchar(max) = ERROR_MESSAGE
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
INSERT INTO Exception.SqlTransaction VALUES (@sp_Name, @ErrorNumber, @ErrorSeverity, @ErrorState,  @ErrorProcedure, @ErrorLine,
@ErrorMessage)

现在应该如何使用EXEC调用原始sp?

1 个答案:

答案 0 :(得分:2)

应该没有括号

text