SQLTeam.com | Weblogs | Forums

TmpTbl with # sign



I have a simple query listed below:

select *
into #TmpTbl
from [Person].[Address]

select * from #TmpTbl

drop table #TmpTbl

I am wondering if there is a way in sql that automate the drop table#TmpTbl if I stop in the middle of the execution process? So I dont have to highlight drop table #TmpTbl
and run to clear this below error msg:

Msg 2714, Level 16, State 6, Line 1
There is already an object named '#TmpTbl' in the database.

Highlight one TmpTbl is not an issue to clear that error but imagine if I have more than 10 tmptbls? Is that a way I add a code to handle this?



drop table #TmpTbl

select *
into #TmpTbl
from [Person].[Address]

select * from #TmpTbl

Then execute all three statements each time. The first time the drop will fail, but that doesn't matter.


Put this at the beginning of your code

IF OBJECT_ID('tempdb..#TmpTbl') IS NOT NULL drop table #TmpTbl;


Thanks gbritton and JamesK. Both additional code and concepts work!


Hi JamesK, how to I add second tmptbl, third and so on if I have more than one tmptbl? Thanks JamesK


I got it JamesK. I just added additional if statement. Thanks JamesK


Hi JamesK,

Question. What is the .. inside the ('tempdb..#TmpTbl') represent for? I am trying to understand the logic.

IF OBJECT_ID('tempdb..#TmpTbl') IS NOT NULL drop table #TmpTbl;

does it mean, if the object inside the tempdb folder where if there is a #TmpTbl called #TmpTbl is NOT NULL, in other word, exist then drop it. Is the .. just the format in SQL instead (, - comma for example?) I am just curious. Thanks James.


Unlike base tables, all temp tables (the ones whose name starts with a #) are created in the tempdb database. tempdb..#TmpTbl allows you to refer to the the temp table named #TmpTbl using the 3-part naming convenion.

OBJECT_ID function lets you retrieve the id of an object. If there is no object that matches the name you pass in, it returns null.