SQL Server Catch异常并继续

ozs*_*gal 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
Run Code Online (Sandbox Code Playgroud)

if(@@error <> 0)在行之后,我想继续执行代码,即使有任何错误,但SQL会向我的应用程序抛出异常,并且IF条件内的代码将不会执行.

有任何想法吗?

Jef*_*nby 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
Run Code Online (Sandbox Code Playgroud)