Home All Groups Group Topic Archive Search About

sql server 2005 error handling

Author
9 Feb 2006 9:55 PM
farshad
I would like to make use of the new error handling in sql server 2005
Could you please see if this sql is ok (It does compile)
CREATE PROCEDURE uspGetData
AS

declare @Error    int
declare @Msg    varchar(128)

set nocount on

begin try
    select
        SectionID,
        SectionTitle
    from
        RISECT01
    order by
        SectionTitle
end try

begin catch
    SET @Msg = 'Cannot retrieve Sections from Table'
    RAISERROR (@Msg, 16, 1)
    RETURN(@@Error)
end catch

set nocount off

Author
9 Feb 2006 11:40 PM
Erland Sommarskog
farshad (fars***@discussions.microsoft.com) writes:
Show quote
> I would like to make use of the new error handling in sql server 2005
> Could you please see if this sql is ok (It does compile)
> CREATE PROCEDURE uspGetData
> AS
>
> declare @Error     int
> declare @Msg     varchar(128)
>
> set nocount on
>
> begin try
>      select
>           SectionID,
>           SectionTitle
>      from
>           RISECT01
>      order by
>           SectionTitle
> end try
>
> begin catch
>      SET @Msg = 'Cannot retrieve Sections from Table'
>      RAISERROR (@Msg, 16, 1)
>      RETURN(@@Error)
> end catch

Depends on what you would want to catch. It would catch a deadlock.
However, assume that the table RISECT01 does not exist. Due to deferred
name resolution, this does not give you any error when you create
the procedure, but of course you get an error when you reach the
SELECT statement. This error will *not* be caught by the error handler,
however, if there is a CATCH handler in the calling scope, that
handler will catch therror.

There is probaly an error in your RETURN statement. You will return
50000, as @@error will be set to this value by the RAISERROR statement.
If you want to return the errnr number of the error that got you
into the handler, you should use error_number() instead.


--
Erland Sommarskog, SQL Server MVP, esq***@sommarskog.se

Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx

AddThis Social Bookmark Button