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.[codesyntax lang=”tsql”] 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 [/codesyntax]