SQL Server Catch Exception and Continued

Ive done the procedure:

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 

After the line if(@@error <> 0) I want to continue executing the code, even if there are any errors, but SQL throws an exception for my application, and the code inside the IF condition will not be executed.

Any ideas?

+6
sql-server
source share
2 answers
 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 
+7
source share

The following will try to run your command. You can put everything that you want to run in the CATCH block, which will be executed only when an error occurs. The remaining code after CATCH will work with or without error.

 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 
0
source share

All Articles