我有一个使用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
答案 0 :(得分:2)
假设你尝试这样的事情
Exec procUpdateFoodTitleConditionDiscount 1,1,'45%'
您的过程的签名阻止执行任何过程。
例如,如果您添加了
begin
PRINT 'foo'
set @errorMessage = 'Discount updated'
'foo'永远不会被打印出来。
如果您想要了解自己描述的行为,则需要将@discountPercentage decimal(4,2),
更改为@discountPercentage varchar(10)
答案 1 :(得分:1)
您无法在proc中捕获此错误:它在您的代码运行之前发生。
这需要在客户端代码中清除。毕竟45%是0.45。 SQL Server根本不擅长这个
你可以将参数更改为varchar并进行一些操作,但这只是愚蠢的