Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 try catch syntax

Author  Topic 

WeeBubba
Starting Member

18 Posts

Posted - 2007-03-14 : 16:15:36
hi there i have 2 questions about the TRY/CATCH statement that i have written below. any advice from more experienced persons would be highly appreciated. thankyou.

1. re the @ErrorMessage variable, i have seen this declared with a datatype of varchar(MAX), nvarchar(2048) and nvarchar(4000). which is the correct one for me to use?

2. do i need the statement 'RETURN @ErrorCode' at the end or is this redundant?

BEGIN CATCH

IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION

DECLARE
@ErrorCode int,
@ErrorMessage nvarchar(4000),
@ErrorSeverity int

SELECT
@ErrorCode = @@ERROR,
@ErrorMessage = ERROR_MESSAGE(),
@ErrorSeverity = ERROR_SEVERITY()

IF EXISTS (SELECT * FROM Users WHERE Username = @Username)
RAISERROR('The username already exists.', 15, 1)
ELSE IF EXISTS (SELECT * FROM Users WHERE Email = @Email)
RAISERROR('The email already exists.', 15, 1)
ELSE
RAISERROR(@ErrorMessage, @ErrorSeverity, 1)

RETURN @ErrorCode

END CATCH

END

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2007-03-14 : 16:28:55
According to SQL Server Books Online, ERROR_MESSAGE() is nvarchar(2048).

If you don't put RETURN @ErrorCode, then you won't get @ErrorCode returned as a return code. It just depends on what you want to do.

Tara Kizer

http://weblogs.sqlteam.com/tarad/
Go to Top of Page

WeeBubba
Starting Member

18 Posts

Posted - 2007-03-14 : 16:47:36
thanks for the quick reply tara.

i'll amend my datatype to nvarchar(2048).

i wasnt sure if the RAISEERROR statement would force the code to exit before it hit the RETURN @ErrorCode statement, that's all.
Go to Top of Page
   

- Advertisement -