Try / Catch无法捕获存储过程中的异常

时间:2015-02-28 11:13:24

标签: stored-procedures error-handling sql-server-2012 try-catch

我正在努力让我的try / catch与我的存储过程一起工作,似乎没有发现错误。我一直在寻找,但没有运气。我想要完成的是在调用存储过程时,如果给出无效值,无值或null,则显示错误号。我试过移动尝试并抓住感觉就像到处都是,但似乎错误可能在“@SomeID as int”行上。我感谢任何帮助。

alter procedure DeleteAcct
@SomeID as int
as
begin try
declare @counter int
set @counter = (select count(SomeDate) from Table1 where SomeID = @SomeID group by SomeID)
begin
	if(@counter > 0)
	begin
	Print 'Testing'
	end
	else 
	begin	
	delete from Table2
	where SomeID = @SomeID
	Print 'Delete successful'
	end
end
end try
begin catch
	print error_number()
end catch

<!-- calling the stored procedure -->
exec DeleteAcct '1231231231221'

<!-- Error received -->
Msg 8114, Level 16, State 5, Procedure DeleteAcct, Line 0
Error converting data type varchar to int.

2 个答案:

答案 0 :(得分:2)

您将param @SomeID声明为int,然后尝试传递字符串!

像这样打电话:

exec DeleteAcct 1231231231221

实际上我怀疑@SomeID应该被声明为varchar

答案 1 :(得分:1)

这个答案很晚,但我们一直在做这个。 您应该尝试/捕获启动器而不是正在执行的SP。

我相信这个解释非常明显,但让我们发展:

  1. 被调用的程序不需要任何try / catch:
  2. 
        alter procedure DeleteAcct
        @SomeID as int
        as
        declare @counter int
        set @counter = (select count(SomeDate) from Table1 where SomeID = @SomeID group by SomeID)
        begin
            if(@counter > 0)
            begin
            Print 'Testing'
            end
            else 
            begin   
            delete from Table2
            where SomeID = @SomeID
            Print 'Delete successful'
            end
        end
    
    1. 需要将启动程序或调用程序放入try / catch块中,以便执行程序中的错误显示在启动程序级别。
    2. 
          begin try
              exec DeleteAcct '1231231231221'
          end try
          begin catch
              print error_number()
          end catch