Jika Anda menggunakan blok try / catch, nomor kesalahan raiserror dengan tingkat keparahan 11-19 akan menyebabkan eksekusi melompat ke blok catch.
Setiap tingkat keparahan di atas 16 adalah kesalahan sistem. Untuk mendemonstrasikan kode berikut, siapkan blok coba / tangkap dan jalankan prosedur tersimpan yang kami anggap akan gagal:
asumsikan kita memiliki tabel [dbo]. [Kesalahan] untuk menahan kesalahan asumsikan kita memiliki prosedur tersimpan [dbo]. [AssumeThisFails] yang akan gagal saat kita menjalankannya
if (object_id('tempdb..
create table
declare @tc as int;
set @tc = @@trancount;
if (@tc = 0)
begin transaction;
else
save transaction myTransaction;
begin try
declare @return_value = '0';
set @return_value = '0';
declare
@ErrorNumber as int,
@ErrorMessage as varchar(400),
@ErrorSeverity as int,
@ErrorState as int,
@ErrorLine as int,
@ErrorProcedure as varchar(128);
exec @return_value = [dbo].[AssumeThisFails]
if (@return_value <> 0)
raiserror('This is my error message', 17, 1);
if (@tc = 0)
commit transaction;
return(0);
end try
begin catch
select
@ErrorNumber = ERROR_NUMBER(),
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY(),
@ErrorState = ERROR_STATE(),
@ErrorLine = ERROR_LINE(),
@ErrorProcedure = ERROR_PROCEDURE();
insert
values (@ErrorNumber, @ErrorMessage, @ErrorSeverity, @ErrorState, @ErrorLine, @ErrorProcedure);
if (@tc = 0)
begin
if (XACT_STATE() <> 0)
begin
select * from
rollback transaction;
insert into [dbo].[Errors] (ErrorNumber, ErrorMessage, ErrorSeverity, ErrorState, ErrorLine, ErrorProcedure)
select * from
insert [dbo].[Errors] (ErrorNumber, ErrorMessage, ErrorSeverity, ErrorState, ErrorLine, ErrorProcedure)
values (@ErrorNumber, @ErrorMessage, @ErrorSeverity, @ErrorState, @ErrorLine, @ErrorProcedure);
return(1);
end
end
if (XACT_STATE() = 1)
begin
rollback transaction myTransaction;
if (object_id('tempdb..
insert
values (@ErrorNumber, @ErrorMessage, @ErrorSeverity, @ErrorState, @ErrorLine, @ErrorProcedure);
else
raiserror(@ErrorMessage, @ErrorSeverity, @ErrorState);
return(2);
end
else if (XACT_STATE() = -1)
begin
rollback transaction;
if (object_id('tempdb..
insert
values (@ErrorNumber, @ErrorMessage, @ErrorSeverity, @ErrorState, @ErrorLine, @ErrorProcedure);
else
raiserror(@ErrorMessage, @ErrorSeverity, @ErrorState);
return(3);
end
end catch
end
RAISERROR
sebenarnya akan menghentikan eksekusi jika tingkat keparahan disetel ke 17 atau 18, bukan 16