【问题标题】:How does one catch the error message "Error Converting data type varchar to decimal"如何捕获错误消息“将数据类型 varchar 转换为十进制时出错”
【发布时间】:2011-02-02 15:17:32
【问题描述】:

我有一个使用 try catch 块执行更新的存储过程。列 (discountPercentage) 设置为十进制数据类型。如果用户将 discountPercentage 作为小数以外的任何值插入,例如如果他们尝试插入 45%,我希望存储过程能够捕获。我正在使用 ERROR_MESSAGE 函数,由于某种原因它没有捕获错误消息。我仍然收到指出“将数据类型 varchar 转换为十进制时出错”的错误消息。到目前为止,这是我的代码:

alter procedure procUpdateFoodTitleConditionDiscount
(
    @foodTitleId int,
    @conditionId int,
    @discountPercentage decimal(4,2),
    @errorMessage varchar(100) output
)
as 
begin
set @errorMessage = 'Discount updated'  

begin try
    update Discount
    set discountPercentage = @discountPercentage
    where foodTitleId = @foodTitleId and conditionId = @conditionId

    if (@@ROWCOUNT = 0)
    begin
        set @errorMessage = 'Update not successful.'
    end
end try

begin catch
    if (ERROR_MESSAGE () like '%converting%')
    begin
        set @errorMessage = 'Please Insert Discount Percentage as a Decimal (ex 0.45)'
    end
end catch

end;

declare @errorMessageValue varchar (100)
execute procUpdateFoodTitleConditionDiscount
    @foodTitleId = '104', 
    @conditionId = '4',
    @discountPercentage = '45%', 
    @errorMessage = @errorMessageValue output
print @errorMessageValue

【问题讨论】:

    标签: sql-server tsql


    【解决方案1】:

    假设你尝试这样的事情

    Exec procUpdateFoodTitleConditionDiscount 1,1,'45%'

    您的过程的签名正在阻止执行任何过程。

    例如,如果您添加了

    begin
    PRINT 'foo'
    
    set @errorMessage = 'Discount updated'  
    

    'foo' 永远不会被打印。

    如果您想要您描述的行为,您需要将@discountPercentage decimal(4,2), 更改为@discountPercentage varchar(10)

    【讨论】:

    • 是的;您收到的错误消息来自将该非数字字符串传递给存储过程的数字 discountPercentage 参数时尝试的转换,因此它不在您的 try 块中。代码永远不会走那么远。
    【解决方案2】:

    您不能在 proc 中捕获此错误:它发生在您的代码运行之前。

    这需要在客户端代码中清理。毕竟 45% 是 0.45。 SQL Server 根本不擅长这个

    可以将参数更改为 varchar 并进行一些操作,但这很愚蠢

    【讨论】:

      猜你喜欢
      • 2015-05-11
      • 2013-04-27
      • 2021-08-13
      • 1970-01-01
      • 2012-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多