Solved

SQL TRY/CATCH testing for existence.

Posted on 2011-09-02
2
223 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

Zoho SalesIQ

Hassle-free live chat software re-imagined for business growth. 2 users, always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION: While tying your database objects into builds and your enterprise source control system takes a third-party product (like Visual Studio Database Edition or Red-Gate's SQL Source Control), you can achieve some protection using a sing…
In SQL Server, when rows are selected from a table, does it retrieve data in the order in which it is inserted?  Many believe this is the case. Let us try to examine for ourselves with an example. To get started, use the following script, wh…
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…

920 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

14 Experts available now in Live!

Get 1:1 Help Now