question

liton avatar image
liton asked

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.
t-sqlerror-handling
1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Can you provide a sample of the code that you are working with please?
3 Likes 3 ·
TimothyAWiseman avatar image
TimothyAWiseman answered
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
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Grant Fritchey avatar image
Grant Fritchey answered
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.
1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

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.
0 Likes 0 ·
liton avatar image
liton answered
Thanks TimothyAWiseman. This is exactly what I was looking for.
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.