We have 100s of proc which are creating temp tables and Not dropping them. Many of the builds are in production. We would like to have SQL query to drop these after N (=2) days and schedule it. Is there any way to do that? Below is sample code to iterate from old temp tables but its not able to delete the tables if I run it.
USE tempdb;
DECLARE @SQL VARCHAR(MAX)
set @SQL =
(
SELECT STUFF(
(
SELECT ' DROP TABLE ' + cast(name as varchar(200))
FROM tempdb.sys.tables where create_date < '2019-12-10 00:00:00.000'
FOR XML PATH('')
),1, 1, '')
);
PRINT @SQL;