伊夫遵循的程序:的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代码条件不会执行。
任何想法?
你不想使用@@标识,它是一个不安全的命令,将messwith你dataintegrity如果你添加触发器其插入到其他表的表。改用OUTPUT或scope_identity()。 – HLGEM 2010-12-14 18:53:11
@@ identity是什么问题?我如何使用OUTPUT? – ozsenegal 2010-12-14 19:00:25
@@ identity为您提供生成的LAST身份值,该值不一定是您想要的身份值。如果tb_cidades上的触发器插入到历史记录/日志表中,并且其上具有标识列,那么您将获得该标识值而不是为tb_cidades表生成的标识值。通过使用SCOPE_IDENTITY(),您可以获得当前“范围”内生成的身份值,该值将位于tb_cidades上。 – 2010-12-14 19:39:14