?
Solved

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

Posted on 2003-11-30
12
Medium Priority
?
1,395 Views
Last Modified: 2007-12-19

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?

0
Comment
Question by:PascuaD
  • 3
  • 3
  • 2
  • +1
10 Comments
 
LVL 15

Expert Comment

by:Ralf Klatt
ID: 9846440
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
 
LVL 1

Expert Comment

by:yuniar
ID: 9846857
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
 
LVL 15

Expert Comment

by:Ralf Klatt
ID: 9846923
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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 18

Expert Comment

by:nigelrivett
ID: 9846949
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
 

Author Comment

by:PascuaD
ID: 9846992
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
 

Author Comment

by:PascuaD
ID: 9847056
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
 
LVL 15

Accepted Solution

by:
Ralf Klatt earned 160 total points
ID: 9848468
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
 
LVL 18

Expert Comment

by:nigelrivett
ID: 9848522
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
 

Author Comment

by:PascuaD
ID: 9849044
Thanks guys for the additional comments/suggestions.




0
 
LVL 1

Assisted Solution

by:yuniar
yuniar earned 160 total points
ID: 9849518
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

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Recently we ran in to an issue while running some SQL jobs where we were trying to process the cubes.  We got an error saying failure stating 'NT SERVICE\SQLSERVERAGENT does not have access to Analysis Services. So this is a way to automate that wit…
An alternative to the "For XML" way of pivoting and concatenating result sets into strings, and an easy introduction to "common table expressions" (CTEs). Being someone who is always looking for alternatives to "work your data", I came across this …
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Viewers will learn how the fundamental information of how to create a table.
Suggested Courses

807 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question