Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop temp table if it exists on SQL Azure

Is there better way to drop temp table on Azure SQL?

BEGIN TRY
    DROP TABLE #customMap
END TRY
BEGIN CATCH
END CATCH

Maybe there is no need to drop temp tables on Azure SQL since tables are dropped when session is ended.

This

if (OBJECT_ID('#candidates')) is not null
begin
    drop table #candidates;
end;

or this

if (OBJECT_ID('tempdb..#candidates')) is not null
begin
    drop table #candidates;
end;

does not work.

like image 325
Fosna Avatar asked Nov 01 '25 21:11

Fosna


2 Answers

In Azure SQL Database you can use DROP IF EXISTS (DIE) syntax:

create table #temp (id int)

drop table if exists #temp
like image 79
Jovan MSFT Avatar answered Nov 04 '25 11:11

Jovan MSFT


IF OBJECT_ID('tempDB..#myTempName','U') IS NOT NULL
   drop table #myTempName 

temporary tables are created in tempDB, not whatever DB you're currently using as the default db.

like image 21
Marc B Avatar answered Nov 04 '25 11:11

Marc B