Question

Often, when testing stored procedure code for improvement or change requests, I find myself copying and pasting blocks of the code directly into Management Stuido, tweaking the variables and running them.

However, a lot of the time the code is reliant on temp tables (not table variables) which are created during the stored procedure run. In normal course of operations those tables are disposed on when the sproc is finished executing, but when they're run directly in management studio, they obviously stick around in memory.

That means I can't just re-execute the code on each tweak, because it tries to re-create the tables and causes an error.

Sometimes it's easy enough to tweak the code to avoid this, but when there's a lot of tables that's a bit impractical. There's always copying and pasting the code into a new query window each time, but that gets annoying really quickly.

Is there any way to simply clear out temp tables from the memory in the current session, so you can just start afresh on each run?

Was it helpful?

Solution

The comments cover the most frequent methods, which for completeness are:

  1. Right click in query window and go to Connection > Change Connection, causing the session to refresh, hence dropping the temp tables
  2. Copy SQL to a new window does the same

When testing, I frequently have block commented drop commands at the top of the testing window that you can select and run (Hit F5), like so:

/*    
DROP TABLE #TEMP1
DROP TABLE #TEMP2    
*/

SELECT TOP 1 * 
INTO #TEMP1
FROM Users

SELECT TOP 1 * 
INTO #TEMP2
FROM Users

So you just simply highlight the lines between the comments and run the selected statements.

Usually if I'm happy the entire query will run, I'll just have the DROP statements at the end, so I can re-run over and over, unless of course you want to interrogate the #TEMP tables.

OTHER TIPS

A small stored procedure to put in your project.

--
-- Drop all #temporary tables of active connexion.
--
CREATE PROCEDURE DropTempTables
AS
BEGIN
    SET NOCOUNT ON;

    declare @sql nvarchar(max)
    
    SELECT 
        @sql = concat(@sql, 'DROP TABLE ', SUBSTRING(t.name, 1, CHARINDEX('___', t.name)-1), '; ')
    FROM tempdb.sys.tables AS t
    WHERE t.name LIKE '#%[_][_][_]%'
    AND t.[object_id] = OBJECT_ID('tempdb..' + SUBSTRING(t.name, 1, CHARINDEX('___', t.name)-1))

    exec sp_executesql @sql
END
GO

Then you can use it like that.

exec DropTempTables

SELECT * 
INTO #myTempTable
FROM table

SELECT * 
INTO #myTempTable
FROM table
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top