Sunday, January 17, 2010

Capture Error Message on Procedure

When we want to make a procedure from sql, sometimes we need to capture the error message on procedure. It will allow us to make an history into the physical table on databases. Here the simulation :

---------------------------------
if exists(select 1 from sys.objects where name = 't_test') drop table t_test

create table t_test
(
id int not null,
primary key(id)
)
go
---------------------------------
if exists(select 1 from sys.objects where name = 't_msg') drop table t_msg

create table t_msg
(
id int identity(1,1) not null,
msg varchar(max) not null,
date datetime,
primary key(id)
)
go
---------------------------------
if exists(select 1 from sys.objects where name = 'sp_addTest') drop procedure sp_addTest
---------------------------------
create procedure sp_addTest
@id int
as
begin

begin try
begin tran
insert into t_test values(@id)
commit tran
end try
begin catch
declare @err_msg varchar(max), @err_proc varchar(max)
set @err_msg = ERROR_MESSAGE()
set @err_proc = ERROR_PROCEDURE()
rollback tran

insert t_msg(msg,date) select 'sp_addTest Error : '+ltrim(rtrim(@err_msg))+ 'Error in '+@err_proc,getdate()
end catch

end
go
---------------------------------
exec sp_addTest 2
go

exec sp_addTest 3
go

exec sp_addTest 4
go

exec sp_addTest 2
go

select * From t_test



select * From t_msg




the message is "sp_addTest Error : Violation of PRIMARY KEY constraint 'PK__t_test__1CA7377D'. Cannot insert duplicate key in object 'dbo.t_test'.Error in sp_addTest"

Happy Code ^_^"

No comments:

Post a Comment