Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropping table in Sql-Server using try-catch block

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)
like image 635
anonxen Avatar asked Jan 18 '26 02:01

anonxen


1 Answers

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

like image 142
Pream Avatar answered Jan 20 '26 17:01

Pream



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!