2010-12-14 91 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