hi all,
not sure this is the correct section to post this, but couldn't find a more appropriate one.
we are debating on sql exception handling usage and we could'nt have an agreement on whether we should trap constraint exceptions with a try-catch block or check them before executing insert/update/delete statements.
one of my collegues insist that constraint exceptions should be considered in terms of error handling rather than exception handling and should not be handled by sql exception handling mechanism. He suggests to use "if exists" before every insert/update/delete as a constraint check inside a try block, so that only the records which are changed just after the if exists statement had executed may cause exception.
Briefly, it boils down to this:
begin try
insert into table_with_some_constraint_that_is_about_to_be_violated t
values a,b,c
end try
begin catch
IF (error_number() == 2627)
return 1000 -- our inproc. return code for duplicate.
ELSE
RAISERROR('error_message_here', 11,1)
end catch
OR
begin try
IF (NOT EXISTS( SELECT * FROM table_with_some_constraint_that_is_about_to_be_violated t
WHERE x=a AND y=b AND z=c))
insert into table_with_some_constraint_that_is_about_to_be_violated t
values a,b,c
ELSE
return 1000
end try
begin catch
IF (error_number() == 2627)
return 1000 -- our inproc. return code for duplicate.
ELSE
RAISERROR('error_message_here', 11,1)
end catch
thanks in advance