2010-12-14 88 views
6

伊夫遵循的程序:的SQL Server捕获异常,并继续

alter procedure sp_insert_cities 
(
    @txt_nome_cidade varchar(300), 
    @txt_nome_estado varchar(150) = null, 
    @txt_pais varchar(150) = null, 
    @int_id_cidade int output 
) 
as 
begin 
      //Here an exception may occur 
      insert into tb_cidades values(
      @txt_nome_cidade, 
      @txt_nome_estado, 
      @txt_pais) 

      set @int_id_cidade = @@identity 

      //Here i want to catch exception and continue executing the proc 
      if(@@error <> 0) 
      begin 
      select @int_id_cidade = int_id_cidade 
      from tb_cidades 
      where 
      txt_nome_cidade = @txt_nome_cidade 
      end 

if(@@error <> 0)线,我要继续执行代码,即使有任何错误,但SQL抛出一个异常,我的应用程序和内部IF代码条件不会执行。

任何想法?

+1

你不想使用@@标识,它是一个不安全的命令,将messwith你dataintegrity如果你添加触发器其插入到其他表的表。改用OUTPUT或scope_identity()。 – HLGEM 2010-12-14 18:53:11

+0

@@ identity是什么问题?我如何使用OUTPUT? – ozsenegal 2010-12-14 19:00:25

+0

@@ identity为您提供生成的LAST身份值,该值不一定是您想要的身份值。如果tb_cidades上的触发器插入到历史记录/日志表中,并且其上具有标识列,那么您将获得该标识值而不是为tb_cidades表生成的标识值。通过使用SCOPE_IDENTITY(),您可以获得当前“范围”内生成的身份值,该值将位于tb_cidades上。 – 2010-12-14 19:39:14

回答

7
BEGIN TRY 
     insert into tb_cidades values( 
      @txt_nome_cidade, 
      @txt_nome_estado, 
      @txt_pais) 

      set @int_id_cidade = @@identity 
END TRY 

BEGIN CATCH 
      select @int_id_cidade = int_id_cidade 
      from tb_cidades 
      where 
      txt_nome_cidade = @txt_nome_cidade 
END CATCH 
+1

摆脱@@身份,使用SCOPE_IDENTITY() – 2010-12-14 18:57:59

+1

@@身份v。SCOPE_IDENTITY()不是问题的一部分(虽然我同意你的看法) – 2010-12-14 20:34:58

+0

即使认为OP不会询问@@身份,这是原始代码的一个明显问题,并且很容易修复。 – 2010-12-15 20:28:37

0

以下将尝试运行您的命令。您可以将任何想要运行的内容放入CATCH块中,只有在发生错误时才会执行该操作。 CATCH之后的其余代码将在发生错误或无错误时运行。

BEGIN TRY 
    insert into tb_cidades values(
    @txt_nome_cidade, 
    @txt_nome_estado, 
    @txt_pais) 

     set @int_id_cidade = @@identity 
END TRY 

BEGIN CATCH 
    PRINT 'Error occurred' 

END CATCH 

if(@@error <> 0) 
begin 
select @int_id_cidade = int_id_cidade 
from tb_cidades 
where 
txt_nome_cidade = @txt_nome_cidade 
end