sqlor
February 18, 2021, 8:27pm
1
Hello
When I re-run a query, it says that the temp table objects already exist so I have to open a new window in SSMS.
Is there a command to clear all temp tables after the query ends or before it begins without having to drop one by one?
I use T-SQL
Thanks
Yes - you can put code in to drop the tables if they exist:
Drop Table If Exists #myTempTable;
yosiasz
February 18, 2021, 9:36pm
3
This answer that was already given to you by @robert_volk should help guide you. Also read the documentation of temp tables
In Microsoft SQL Server, a temporary table is specified with a # prefix character:
CREATE TABLE #myTable(col1 int not null);
Such a table is only accessible/visible in the session that created it. A global temporary table uses ## prefix:
CREATE TABLE ##globalTable(col2 int not null);
The global temp table can be accessed by another session. Both types of temporary tables are automatically destroyed when all sessions that accessed them terminate.
The single # temporary table would meet your …
Ifor
February 18, 2021, 9:42pm
4
This generates the list for the current session:
SELECT 'DROP TABLE ' + LEFT([name], CHARINDEX('_', [name]) -1) + ';'
FROM tempdb.sys.objects
WHERE [name] LIKE '#%'
AND CHARINDEX('_', [name]) > 0
AND [type] = 'U'
AND NOT object_id('tempdb..' + [name]) IS NULL;
please see this link which shows WHAT to do
1 Like