2010-12-14 15 views
6

Ive seguire la procedura:SQL eccezione Cattura Server e continuare

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 

Dopo if(@@error <> 0) linea, voglio continuare l'esecuzione di codice, anche se ci sono errori, ma SQL genera un'eccezione alla mia richiesta e il codice all'interno IF la condizione non verrà eseguita.

Qualche idea?

+1

Se non si desidera utilizzare @@ identità, è un comando non sicuro che il vostro messwith dataintegrity se mai aggiungere trigger alla tabella che inserire ad altre tabelle. Usa invece OUTPUT o scope_identity(). – HLGEM

+0

qual è il problema con @@ identity? E come utilizzo OUTPUT? – ozsenegal

+0

@@ identity ti dà l'ULTIMO valore di identità generato, che non è necessariamente il valore di identità che desideri. se si ha un trigger su tb_cidades che si inserisce in una tabella cronologia/registro e su di essa è presente una colonna Identity, si ottiene quel valore di identità e non il valore di identità generato per la tabella tb_cidades. Usando SCOPE_IDENTITY() ottieni il valore dell'identità generato all'interno del tuo "scope" corrente, che sarebbe su tb_cidades. –

risposta

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

sbarazzarsi di @@ identity, utilizzare SCOPE_IDENTITY() –

+1

@@ identity v. SCOPE_IDENTITY() non faceva parte della domanda (anche se sono d'accordo con te) –

+0

ha anche pensato che l'OP non chiedesse l'identità @@, è un problema ovvio con il codice originale e facilmente risolto. –

0

Quanto segue cercherà di eseguire il comando. Puoi mettere tutto ciò che vuoi eseguire nel blocco CATCH, che verrà eseguito solo quando si verifica un errore. Il codice rimanente dopo il CATCH verrà eseguito con errore o senza errori.

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