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
 SQL Server 2000 Forums
 Transact-SQL (2000)
 How to use TRY CATCH in SQL2005

Author  Topic 

hornet
Yak Posting Veteran

96 Posts

Posted - 2006-09-07 : 05:25:14
Hi!
I've read that is possible to use TRY CATCH in TSQL2005.
I tried to do it, but vainly.
Maybe neccessary to include smth.
Thanks!

chiragkhabaria
Master Smack Fu Yak Hacker

1907 Posts

Posted - 2006-09-07 : 05:26:15
post wat you tried.

Chirag
Go to Top of Page

hornet
Yak Posting Veteran

96 Posts

Posted - 2006-09-07 : 05:39:52
I tried it at home where i have SQL2005, but now I'm working so I can type approximately

I'm using this in procedure.
Something like this:

CREATE PROCEDURE .........
........

BEGIN
BEGIN TRY
INSERT INTO Cities ...........
END TRY
BEGIN CATCH

END CATCH
END

Go to Top of Page

chiragkhabaria
Master Smack Fu Yak Hacker

1907 Posts

Posted - 2006-09-07 : 05:42:56
From BOL 2005

BEGIN TRY
SELECT *
FROM sys.messages
WHERE message_id = 21;
END TRY
GO
-- The previous GO breaks the script into two batches,
-- generating syntax errors. The script runs if this GO
-- is removed.
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber;
END CATCH;

OR

USE AdventureWorks;
GO

-- Verify that the stored procedure does not exist.
IF OBJECT_ID ('usp_GetErrorInfo', 'P') IS NOT NULL
DROP PROCEDURE usp_GetErrorInfo;
GO

-- Create procedure to retrieve error information.
CREATE PROCEDURE usp_GetErrorInfo
AS
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() as ErrorState,
ERROR_PROCEDURE() as ErrorProcedure,
ERROR_LINE() as ErrorLine,
ERROR_MESSAGE() as ErrorMessage;
GO

BEGIN TRY
-- Generate divide-by-zero error.
SELECT 1/0;
END TRY
BEGIN CATCH
-- Execute the error retrieval routine.
EXECUTE usp_GetErrorInfo;
END CATCH;
GO



Chirag
Go to Top of Page

eyechart
Master Smack Fu Yak Hacker

3575 Posts

Posted - 2006-09-07 : 15:17:28
here is a pretty good article on error handling using TRY/CATCH blocks that I ran across recently http://sqljunkies.com/Article/E28ED88D-1780-4F6E-9810-2B88B382C934.scuk



-ec
Go to Top of Page
   

- Advertisement -