3

The code below works and is quite precise, but is it OK to do it like this as against the other 'standard' ways ?

--Drop table if exists
begin try
    drop table #temp
end try

begin catch 
    print 'table does not exist'
end catch

--Create table
create table #temp(a int, b int)
4
  • 1
    It all depends on your requirements. If you are just working with a temporary table then Pream's answer is as good as any. Your technique would give feedback on whether the table existed, and that feedback may be useful Commented Mar 6, 2017 at 10:17
  • 1
    Catch blocks are brilliant if you intend to take action when/if an exception occurs. If there is no additional action, you could argue it's just extra typing. In this case, I often don't care if the temp exists or not. I am only checking to avoid an error. With that in mind, the IF NOT EXISTS/OBJECT_ID IS NULL methods are more concise. Commented Mar 6, 2017 at 10:22
  • @destination-data Looks like Try catch is overkill here. If one needs additional actions when table doesn't exist if ... begin additional-actions end will do. Commented Mar 6, 2017 at 10:27
  • I am sorry I did not mean just temporary tables, I just want feedback on whether this would be a good way to drop-create any table including temp ones. Commented Mar 6, 2017 at 11:37

2 Answers 2

6

It is better to use

If Object_Id('Tempdb..#temp') Is Not Null
Drop Table #temp
create table #temp

As you intend to create a #temp Table ultimately which does not require try catch to give a error message that #temp Table does not exists

if the create statement was inside the try, it may have some use

Sign up to request clarification or add additional context in comments.

4 Comments

Why? I'm not necessarily disagreeing, but can you explain the benefits this approach offers?
Hi @destination-data, By the look of the code in the question, anonxen ultimately wants to create a temp table, which does not require try catch to give a error message that tempTable does not exists, in case if the create statement was inside the try, it may have some use
If your answer included that description, I'd definitely upvote it.
@destination-data, There you go!
0

Use EXISTS statement, IF tables exists then only drop table. Otherwise create table directly:

BEGIN TRY
  IF Object_Id('Tempdb..#temp') Is Not Null
     DROP Table #temp
  CREATE table #temp
END try
BEGIN CATCH
  PRINT 'table does not exist'
END CATCH

1 Comment

I'm getting older, I even started using glasses around the house and not just in front of the computer. I other words, I could be getting blind, but where exactly is EXISTS used in this suggestion? it says not null :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.