Solved

IF NOT EXISTS and SELECT INTO

Posted on 2009-07-07
6
266 Views
Last Modified: 2012-05-07
How come when I have the following statement twice in one SQL batch, it gives me an error.  If I open an query analyzer and run them one at a time (maintaining an open connection to preserve temp table) it does not give me an error.

This code is simplified for this post - but there is an automated set of routines which generate the SQL scripts and so this TempTable could be created multiple times.  To avoid that, I want to check if it exists.  

Why will these not work when run together but will work fine when run separately (again in same connection so the second statement actually sees that the first created the table).

The error I get states:
There is already an object named '#TEMP_NAMEHERE' in the database.

Any help is appreciated.

IF NOT EXISTS (SELECT * FROM tempdb..sysobjects WHERE name LIKE '#TEMP_NAMEHERE____%') BEGIN SELECT [FIELD] AS KEYVALUE INTO [#TEMP_NAMEHERE] FROM Database..Table WHERE WhereClause END
 

 IF NOT EXISTS (SELECT * FROM tempdb..sysobjects WHERE name LIKE '#TEMP_NAMEHERE____%') BEGIN SELECT [FIELD] AS KEYVALUE INTO [#TEMP_NAMEHERE] FROM Database..Table WHERE WhereClause END

Open in new window

0
Comment
Question by:jport88
6 Comments
 
LVL 75

Expert Comment

by:Aneesh Retnakaran
ID: 24800368
try this way
IF OBJECT_ID('tempdb..#TEMP_NAMEHERE') IS NOT NULL
  BEGIN SELECT [FIELD] AS KEYVALUE INTO [#TEMP_NAMEHERE] FROM Database..Table WHERE WhereClause END
0
 
LVL 2

Author Comment

by:jport88
ID: 24800406
Still had issue.  I think the issue may actually be that SQL Server does not allow thre same TEMP table to be created in a SQL batch more than once: http://www.informit.com/articles/article.aspx?p=25288&seqNum=4

Meaning I would need to not store it as a TEMP table.

Does that make sense?
0
 
LVL 75

Expert Comment

by:Aneesh Retnakaran
ID: 24800420
why dont you create the table first and insert data

IF OBJECT_ID('tempdb..#TEMP_NAMEHERE') IS NOT NULL
create table #Temp_NameHere (Field int  )
 insert INTO [#TEMP_NAMEHERE]
 SELECT [FIELD] FROM Database..Table WHERE WhereClause
0
Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

 
LVL 57

Expert Comment

by:Raja Jegan R
ID: 24800426
You can try dropping that #temp table if you want to create it several times right.

if exists ( select * from information_schema.tables where table_name = '#temp')
drop table #temp
go

Now include this wherever you need to create that temp table.

Hope this helps
0
 
LVL 15

Accepted Solution

by:
rob_farley earned 500 total points
ID: 24800528
Unfortunately there's a bug in the SQL parser, so that it won't realise you've just dropped the temporary table before you try to recreate it (when you save a stored procedure that drops an object just before populating it with SELECT ... INTO ...)

Best is to CREATE the temporary table at the start, use INSERT statements throughout, and then DROP it at the end.

Hope this helps,

Rob
0
 
LVL 57

Expert Comment

by:Raja Jegan R
ID: 24800723
Ignore my earlier script..

Use this one to drop #temp table before it is created again:

if OBJECT_ID('tempdb..#test') is not NULL
DROP TABLE #temp
go
0

Featured Post

Control application downtime with dependency maps

Visualize the interdependencies between application components better with Applications Manager's automated application discovery and dependency mapping feature. Resolve performance issues faster by quickly isolating problematic components.

Question has a verified solution.

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

Suggested Solutions

If you having speed problem in loading SQL Server Management Studio, try to uncheck these options in your internet browser (IE -> Internet Options / Advanced / Security):    . Check for publisher's certificate revocation    . Check for server ce…
In SQL Server, when rows are selected from a table, does it retrieve data in the order in which it is inserted?  Many believe this is the case. Let us try to examine for ourselves with an example. To get started, use the following script, wh…
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

920 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now