【问题标题】:SQL Server 2012 error handling in stored procedure存储过程中的 SQL Server 2012 错误处理
【发布时间】:2014-08-28 07:42:31
【问题描述】:
ALTER PROCEDURE Ins2(@id   INT,@name NVARCHAR(50)) 
AS 
  BEGIN 
      BEGIN try 
          INSERT INTO abc (id, name) 
          VALUES (@id, @name) 
      END try 

      BEGIN catch 
          INSERT INTO exception 
          VALUES (Error_number(), 
                  Error_severity(), 
                  Error_state(), 
                  Error_procedure(), 
                  Error_line(), 
                  Error_message(), 
                  Getdate()) 

          SELECT * 
          FROM   exception 
      END catch 
  END 

错误:

消息 8152,级别 16,状态 13,过程 ins2,第 19 行
字符串或二进制数据将被截断。
声明已终止。

在上面的存储过程中idabc 表中的主键.. 在运行此程序时,我想在错误表中插入错误详细信息(异常).. 但我收到上述错误..

【问题讨论】:

  • 发布您的异常表的表架构。

标签: sql-server


【解决方案1】:

错误只是由于字段长度。插入的数据包含的长度大于字段长度。 检查“abc”和“exception”表中的字段长度。 希望这会对你有所帮助。

【讨论】:

    【解决方案2】:

    我怀疑您的 catch 块中出现错误。 您能否确认所有 char 列的长度足以容纳您尝试插入异常表的数据? 例如,应该存储错误消息的列的大小可能小于错误消息。 您可以将其设置为 VARCHAR(MAX)。

    【讨论】:

    • 这更像是一个评论而不是一个答案。
    • 我对数据类型进行了更改..我得到了输出。
    【解决方案3】:

    问题在于您正在插入表格的数据的长度。 @nume 参数长 50 个字符(因为它是 nvarchar(50) ),abc 表中的名称可能是?未设置为 nvarchar(50) 或更大或格式不同。

    如果你不能修改表格的结构我建议你修剪参数。

    转到你的 abc 表,选择它并单击 ALT+F1,查看列名并检查它是 varchar 还是 nvarchar 以及它的长度。

    ALTER PROCEDURE Ins2(@id   INT,@name NVARCHAR(50)) 
    AS 
    Declare @sName nvarchar( <insert the lenght of the column name from table abc> )
        set @sName = (SUBSTRING(LTRIM(RTRIM(@name),0,49)
      BEGIN 
          BEGIN try 
              INSERT INTO abc (id, name) 
              VALUES (@id, @sName ) 
          END try 
    
          BEGIN catch 
              INSERT INTO exception 
              VALUES (Error_number(), 
                      Error_severity(), 
                      Error_state(), 
                      Error_procedure(), 
                      Error_line(), 
                      Error_message(), 
                      Getdate()) 
    
              SELECT * 
              FROM   exception 
          END catch 
      END 
    
    `Declare @sName nvarchar( <insert the lenght of the column name from table abc> )` <--- this declare an variable with the lenght equal to the one from the table abc
        `set @sName = (SUBSTRING(LTRIM(RTRIM(@name),0,49)` <-- select the first 50 chars from the parameter
    

    LTRIM(RTRIM(@name)

    如果参数长度对于表 abc 中的字段名称来说太长,也可能会输出错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-17
      • 1970-01-01
      • 1970-01-01
      • 2019-10-17
      • 2018-10-04
      • 2013-06-04
      • 1970-01-01
      相关资源
      最近更新 更多