Skip to content

Instantly share code, notes, and snippets.

@ststeiger
Created April 22, 2026 12:40
Show Gist options
  • Select an option

  • Save ststeiger/83a6c98514b7ff35d551b8bb36bc92b6 to your computer and use it in GitHub Desktop.

Select an option

Save ststeiger/83a6c98514b7ff35d551b8bb36bc92b6 to your computer and use it in GitHub Desktop.
Find leaking temp tables in MSSQL
SELECT TOP 1 *
INTO #foo
FROM T_Benutzer
;
IF OBJECT_ID('tempdb..#NOT_foo') IS NOT NULL DROP TABLE [#foo]; -- this is presumed buggy
-- Find leaking temp-tables
SELECT
-- Strip the mangled suffix to get the original name
SUBSTRING(name, 1, CHARINDEX('_', name + '_', 2) - 1) AS temp_table_name
,name AS internal_name
,create_date
-- FROM tempdb.sys.objects
FROM tempdb.sys.tables
WHERE type = 'U'
AND name LIKE '#%'
-- the function OBJECT_ID is session-scoped
AND OBJECT_ID('tempdb..' + QUOTENAME(name)) IS NOT NULL
-- tempdb.. is the same as tempdb.dbo.
-- The .. means "default schema"
-- AND OBJECT_ID('tempdb.dbo.' + QUOTENAME(name)) IS NOT NULL
ORDER BY create_date;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment