Drop all temporary tables for an instance
The point of temporary tables is that they are.. temporary. As soon as they go out of scope
- #temp create in stored proc : stored proc exits
- #temp created in session : session disconnects
- ##temp : session that created it disconnects
The query disappears. If you find that you need to remove temporary tables manually, you need to revisit how you are using them.
For the global ones, this will generate and execute the statement to drop them all.
declare @sql nvarchar(max)
select @sql = isnull(@sql+';', '') + 'drop table ' + quotename(name)
from tempdb..sysobjects
where name like '##%'
exec (@sql)
It is a bad idea to drop other sessions' [global] temp tables though.
For the local (to this session) temp tables, just disconnect and reconnect again.
Deleting Global Temporary Tables (##tempTable) in SQL Server
Local temporary tables are destroyed when you close your connection to SQL Server. There is no need to manually purge them under normal circumstances. If you maintain a persistent connection, or connection pooling, you may want to get in the habit of dropping temporary tables immediately after use.
Global temporary tables, on the other hand, since they are visible to all users in a given database, are destroyed along with the last connection which references them.
Drop temporary tables created by Amazon Redshift
Solved.
The reason this table kept existing is because its session had an error and it didn't close as expected.
The only way I found to remove this table was rebooting the Redshift instance.
Drop temp table if it exists
Temp #Tables are created in tempdb. Try this:
IF OBJECT_ID('tempdb..#lu_sensor_name_19') IS NOT NULL
BEGIN
DROP TABLE #lu_sensor_name_19
END
CREATE TABLE #lu_sensor_name_19...
SQL Server 2016 added the ability to do the drop in one line:
DROP TABLE IF EXISTS #lu_sensor_name_19
CREATE TABLE #lu_sensor_name_19...
Related Topics
How to Index a Database Column
Get Month and Year from a Datetime in SQL Server 2005
How to Preview a Destructive SQL Query
How to Drop Table Variables in SQL-Server? Should I Even Do This
MySQL Auto-Store Datetime for Each Row
How to Rename a Column in a Database Table Using SQL
How to Identify Port Number of SQL Server
Has Anyone Had Any Success in Unit Testing SQL Stored Procedures
SQL Server Int or Bigint Database Table Ids
Padding Zeros to the Left in Postgresql
Singular or Plural Database Table Names
Using MySQL in Clause as All Inclusive (And Instead of Or)
To Find Infinite Recursive Loop in Cte
Inserting Image into Blob Oracle 10G
How to Use Inno Setup to Update a Database Using .SQL Script
Speed of Paged Queries in Oracle