Recently I came across a post on LinkedIn which required identifying the user who created a temp table. This is an interesting use case and thought I’d write a query of my own. The below script identifies currently logged in users who are executing queries and anytime tables that they might have created.
I figured since Temp tables are only relevant within the section context it didn’t make sense to historically track the presence. I’ve used the transaction log file of the temp database to identify currently created temp tables and map them to session ids that are active based on the transaction ID.
SELECT DISTINCT t.spid , a.AllocUnitName , es.login_name FROM sys.fn_dblog(2,null) t cross apply ( SELECT DISTINCT [TRANSACTION ID], AllocUnitName FROM sys.fn_dblog(2,null) WHERE AllocUnitName like '%#%' and t.[TRANSACTION id] = [TRANSACTION id]) a INNER join sys.dm_exec_sessions es ON es.session_id = t.SPID WHERE t.SPID IS not null