x

Try/Catch problem

I'm using try/catch to detect any errors in my script. If there are no errors then I would like to rename the table at the end of catch and if there are errors then I want to stop it in catch. But when I'm having problem with this. It is renaming the table regardless of errors. Is there any reason for this? I'm assuming try/catch runs the 'exec' statement regardless of errors.
more ▼

asked Dec 08, 2012 at 05:59 AM in Default

liton gravatar image

liton
760 28 36 39

Can you provide a sample of the code that you are working with please?
Dec 10, 2012 at 09:28 AM Fatherjack ♦♦
(comments are locked)
10|1200 characters needed characters left

3 answers: sort voted first

If I understand what you want to do, then you could have a variable to indicate if there was an error. Then set it to True. If your variable is false, rename the table.

In hasty psuedo-code it would look like:

#declare variables

set @therewasanerror = false
begin try
  create table....

  do other stuff
end try
begin catch
  do your error handling
  set @therewasanerror = true
end catch

if not @therewasenrror
  rename table 
more ▼

answered Dec 10, 2012 at 05:54 PM

TimothyAWiseman gravatar image

TimothyAWiseman
15.5k 20 23 32

(comments are locked)
10|1200 characters needed characters left
You should leave the create table statement within the TRY part of the code, not the CATCH. It should only be going to the CATCH part of the code if there is an actual error. That's how it's meant to work.
more ▼

answered Dec 09, 2012 at 12:49 PM

Grant Fritchey gravatar image

Grant Fritchey ♦♦
101k 19 21 74

I am creating the table within the try part but I am renaming the table at the end. If there are errors then I don't want to rename the table.
Dec 10, 2012 at 02:57 PM liton
(comments are locked)
10|1200 characters needed characters left
Thanks TimothyAWiseman. This is exactly what I was looking for.
more ▼

answered Dec 10, 2012 at 08:26 PM

liton gravatar image

liton
760 28 36 39

(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

New code box

There's a new way to format code on the site - the red speech bubble logo will automatically format T-SQL for you. The original code box is still there for XML, etc. More details here.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x987
x21

asked: Dec 08, 2012 at 05:59 AM

Seen: 681 times

Last Updated: Dec 10, 2012 at 08:26 PM