How you do you determine if a temporary table already exists?


I want to make sure that a temporary table (##tempTable) does not exist before I issue the following command:

SELECT * INTO ##tempTable From Table
...
Drop table ##TempTable


Any ideas?

PascuaDAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ralf KlattEmployee in Civil ServiceCommented:
Hi,

Are you sure your tmpTable should not exist? -> Or is it ok if it's just empty ... having no recordsets?

Best regards, Raisor
0
yuniarCommented:
Droping the temp table before do select into would be a good solution for you

if exists (select * from dbo.sysobjects where id = object_id(N'[##tempTable]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [##tempTable]

SELECT * INTO ##tempTable From Table
...
Drop table ##TempTable

hope this help
0
Ralf KlattEmployee in Civil ServiceCommented:
Hi,

@yuniar ... it's good to see that you understood what I was going to suggest ;-))

Well, if the table HAS to be dropped before the select into then yuniar has given the solution!

Otherwise it could look like this:

...
(
...
)
declare @count int
select
@count = count(yourRSUIDName) from yourTempTable

if @count > 0
begin
    delete from yourTempTable
    SELECT * INTO yourTempTable From theOtherTable
    ...
    delete from yourTempTable
end

if @count = 0
begin
    SELECT * INTO yourTempTable From theOtherTable
    ...
    delete from yourTempTable
end


@PasquaD ... I know you said "I want to make sure that a temporary table (##tempTable) does not exist " ... but my question is what is this good for when you delete this temporary table a few thousand times a day and recreate it each time again ... depending on your script usage ...?


Best regards, Raisor

0
Newly released Acronis True Image 2019

In announcing the release of the 15th Anniversary Edition of Acronis True Image 2019, the company revealed that its artificial intelligence-based anti-ransomware technology – stopped more than 200,000 ransomware attacks on 150,000 customers last year.

nigelrivettCommented:
if object_id('tempdb..##tempTable')

But you will probably already have received an error in compiling the SP if the query plan does not already exist.
A drop table may not help as the table will not be dropped if another connection which uses it is still open.

Sounds like you don't want a global temp table here but some other structure.

Should never need to check for the existence of objects in an SP like this - the SP should knokw whether the object has been created and if it isn't there should fail with an error to be investigated.
0
PascuaDAuthor Commented:
When the stored procedure is terminated prematurely then on next time around it’ll generate an error ‘There is already an object named ##tempTable.’
But, If I tried to delete it first and the stored procedure completed successfully then, I get 'Cannot drop the table '##Test', because it does not exist in the system catalog.'

Yuniar suggestion is what I'm looking for.

I need it to be global temporary table as it is created within an EXEC() command - the selections of columns and the selectin criteria is done at run-time. Maybe, there is a better way of doing this. Any comments is greatly appreciated.










0
PascuaDAuthor Commented:
By the way, Yuniar's code didn't work. Modified NigelRivett's with the following and it works.

If not object_id('tempdb..##tempTable') is null Drop Table ##tempTable

Is this OK?
0
Ralf KlattEmployee in Civil ServiceCommented:
Hi,

Well this seems to make sence ... but you should test it with real life data and see if it works ... if not then please give a message ...

This is an example for a static table used as "Temporary Table" (from a productive DB):

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ResultSet_1]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[ResultSet_1]
GO

CREATE TABLE [dbo].[ResultSet_1] (
      [ressetID] [int] IDENTITY (1, 1) NOT NULL ,
      [Standort] [int] NOT NULL ,
      [Referenznummer] [int] NOT NULL ,
      [Kundennummer] [char] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
      [GS_ID_K] [char] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
      [Anforderungnummer] [char] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
      [AnfStandort] [char] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
      [Produktnummer] [char] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
      [Bearbeiter_DB_ID] [char] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
      [EinsatzPLZ] [char] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
      [EinsatzOrt] [char] (100) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
      [EinsatzStrasse] [char] (150) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
      [EinsatzTel] [char] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
      [RMINST] [char] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
      [ProblemBeschreibung] [char] (2048) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
      [ProduktKurz] [char] (512) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
      [AD_MA_ID] [char] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
      [CN_Ziel_KZ] [char] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
      [GarantieAutoDatum] [char] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
      [Einsatznummer] [int] NOT NULL ,
      [DispoDatum] [char] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
      [EinsatzendeDatum] [char] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL
) ON [PRIMARY]
GO

There are some functions which every 5 minutes select data from different servers in different locations ... if any data has changed against the main database updates will be made ...:

/****** Object:  Stored Procedure dbo.DT_Get_Reopened_Calls    Script Date: 22.11.2001 17:27:58 ******/
CREATE PROCEDURE DT_Get_Reopened_Calls AS
update fa set fa.fa21 = 0
WHERE fa.fa21 = 1 AND (fa.fa18 IN
        (SELECT resultset_1.Referenznummer
      FROM resultset_1))

GO

/****** Object:  Stored Procedure dbo.DT_Disable_Routed_Calls    Script Date: 22.11.2001 17:27:58 ******/
CREATE PROCEDURE DT_Disable_Routed_Calls AS
update fa set fa.fa21 = 1
WHERE fa.fa18 NOT IN
        (SELECT resultset_1.Referenznummer
      FROM resultset_1)

GO


At the end of the check the remaining or corrupted data in that static temporary table is just deleted ... this way:

/****** Object:  Stored Procedure dbo.DT_Delete_Corrupted_Records    Script Date: 22.11.2001 18:27:07 ******/
create procedure DT_Delete_Corrupted_Records as
delete from resultset_1

GO



I hope this real example helps you to understand what my suggestion was!

Best regards, Raisor
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
nigelrivettCommented:
If you make sure the connection is dropped whenever there is a problem then the table will be deleted automatically.
As I said if the query plan is re-generated for any reason and the table exists you will get an error unless all access is in dynamic sql or a called SP (I guess this must be the case as the create is a dynamic sql statement).

Maybe a better option would be to create a temp table (#a) with a dummy column and use alter table statements in dynamic sql to get the sructure you want.
You can then call another SP to access it to add and process the data.
see
http://www.nigelrivett.net/AccessTempTablesAcrossSPs.html

This would mean that you don't have to worry about failures as everything will be cleared up on exit from the SP.
0
PascuaDAuthor Commented:
Thanks guys for the additional comments/suggestions.




0
yuniarCommented:
there is another way. Use memory table instead of phisical table. you don't need to check the table does exist or not.

DECLARE XXXX TABLE (
....

)

INSERT INTO XXXX
SELECT * FROM YOURTABLE

DROP TABLE XXXX
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.