【问题标题】:return ERROR_MESSAGE() as output variable in sql server返回 ERROR_MESSAGE() 作为 sql server 中的输出变量
【发布时间】:2016-01-08 19:23:57
【问题描述】:

我想在变量中返回 ERROR_MESSAGE(),但这不起作用,因为就像引发错误但我不希望那样。我想接收返回值(0 ok, 1 error),加上变量@Id中插入的id和这个变量@ErrorMsg中的错误消息,如果有错误

代码如下:

CREATE PROCEDURE [cimpl].[TestInsert]
(
    @TestId INT,
    @Name NVARCHAR(50), 
    @Id INT OUTPUT,
    @ErrorMsg NVARCHAR(4000) = NULL OUTPUT 
)
AS
BEGIN

    DECLARE @ReturnVal int

    SET NOCOUNT ON;

    SET @ReturnVal = 0;
    SET @ErrorMsg = '';

    BEGIN TRY

        -- Insert statement
        INSERT [dbo].[Test]
                (
                  [TestId],
                  [Name]
                )
        VALUES  (
                  @TestId, 
                  @Name,                  
                )

        SET @Id = SCOPE_IDENTITY();

    END TRY

    BEGIN CATCH
        SET @ReturnVal = 1;
        SET @ErrorMsg = ERROR_MESSAGE();
    END CATCH

    RETURN @ReturnVal;

END

来电:

DECLARE @IdIns INT
DECLARE @ErrorM NVARCHAR(4000)
DECLARE @ReturnValue INT = 0

EXEC @ReturnValue = 
    [cimpl].[TransactInsert]
        @TestId= 'ee', --I'm forcing the error
        @Name = 'A', 
        @Id = @IdIns OUTPUT,
        @ErrorMsg = @ErrorM OUTPUT

SELECT @ErrorM
SELECT @ReturnValue
SELECT @IdIns

【问题讨论】:

标签: sql-server


【解决方案1】:

存储过程中的代码应该可以按预期工作。问题是您的测试在 proc 运行之前就抛出了错误,因为您试图将 char 值分配给整数。

在您的测试代码中:

@TestId= 'ee', --I'm forcing the error

这会在解析和编译时引发错误,因为@TestId 被定义为INT,但是ee 是一个不能合并为数字的CHAR(2) 值。

【讨论】:

  • 我不确定你所说的“解析和编译时间”是什么意思,但对我来说,它在调用过程时就坏了。我认为错误发生在将 char 值分配(或绑定或任何调用)给 int 参数时。所以永远不会到达 proc 的错误处理程序,但错误仍然发生在运行时,而不是在编译或解析时。
猜你喜欢
  • 2012-08-11
  • 1970-01-01
  • 2011-07-30
  • 1970-01-01
  • 1970-01-01
  • 2012-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多