Solved

SQL TRY/CATCH testing for existence.

Posted on 2011-09-02
2
222 Views
Last Modified: 2012-06-21
I am reading Microsoft SQL Server 2008 - Database Development book for example 70-433.

On page 155 (in the NOTE TRAPPING ERRORS) it states that "you cannot use TRY...CATCH block to test for an objects existence".

I put this to the test and the TRY did pass control to the CATCH. Here is my code. Can anybody explain this to me...Thanks.

CREATE TABLE dbo.test
(
ID INT NOT NULL PRIMARY KEY
)

BEGIN TRY
CREATE TABLE dbo.test
(
ID INT NOT NULL PRIMARY KEY
)
END TRY
BEGIN CATCH
PRINT 'Table cannot be created'
END CATCH
0
Comment
Question by:Mr_Shaw
2 Comments
 
LVL 28

Accepted Solution

by:
Ryan McCauley earned 500 total points
ID: 36473615
You're testing if an object can be created in your example, and the TRY...CATCH would handle that properly. They're referring to something liek this:

BEGIN TRY
   select * from SomeTableThatDoesntExist
END TRY
BEGIN CATCH
    PRINT 'Table does not exist'
END CATCH

Open in new window


If you execute that, you'll get a SQL Error, not your printed error statement from the CATCH block. What they're saying is that a missing object won't pass control to the CATCH block, it will stop your script in its tracks, so you can't use TRY...CATCH for control flow in this case.
0
 

Author Closing Comment

by:Mr_Shaw
ID: 36473645
thanks
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Suggested Solutions

by Mark Wills Attending one of Rob Farley's seminars the other day, I heard the phrase "The Accidental DBA" and fell in love with it. It got me thinking about the plight of the newcomer to SQL Server...  So if you are the accidental DBA, or, simp…
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now