Tuesday, March 27, 2012

determine if temp table exists

I need to determine a way to search if a tempory table exist before atteptin
g
to read a record from it.
The only way I know of is to perform the following:
if exists(select * from tempdb..sysobjects where name like '#tablename%'
and type='U')
However, if there are multiple sessions on the same machine, this may pass
but the current session doesn't have an existing temporary table. Is there
a
way to determine that a temporary table listed in sysobjects is for the
current session?Try:
IF OBJECT_ID('tempdb..#tablename') IS NOT NULL
Adam Machanic
SQL Server MVP
http://www.datamanipulation.net
--
"Lee" <Lee@.discussions.microsoft.com> wrote in message
news:12A99761-D2FD-4CE8-A6C5-DFA8673B5D9D@.microsoft.com...
> I need to determine a way to search if a tempory table exist before
attepting
> to read a record from it.
> The only way I know of is to perform the following:
> if exists(select * from tempdb..sysobjects where name like '#tablename%'
> and type='U')
> However, if there are multiple sessions on the same machine, this may pass
> but the current session doesn't have an existing temporary table. Is
there a
> way to determine that a temporary table listed in sysobjects is for the
> current session?|||if object_id('tempdb..#tmp','U') is not null
print('#tmp exists')
else
print('#tmp does not exist')
-oj
"Lee" <Lee@.discussions.microsoft.com> wrote in message
news:12A99761-D2FD-4CE8-A6C5-DFA8673B5D9D@.microsoft.com...
>I need to determine a way to search if a tempory table exist before
>attepting
> to read a record from it.
> The only way I know of is to perform the following:
> if exists(select * from tempdb..sysobjects where name like '#tablename%'
> and type='U')
> However, if there are multiple sessions on the same machine, this may pass
> but the current session doesn't have an existing temporary table. Is
> there a
> way to determine that a temporary table listed in sysobjects is for the
> current session?

No comments:

Post a Comment