Solved

IF NOT EXISTS and SELECT INTO

Posted on 2009-07-07
6
265 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 57

Expert Comment

by:Raja Jegan R
Comment Utility
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 14

Accepted Solution

by:
rob_farley earned 500 total points
Comment Utility
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
Comment Utility
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

Free Gift Card with Acronis Backup Purchase!

Backup any data in any location: local and remote systems, physical and virtual servers, private and public clouds, Macs and PCs, tablets and mobile devices, & more! For limited time only, buy any Acronis backup products and get a FREE Amazon/Best Buy gift card worth up to $200!

Join & Write a Comment

Suggested Solutions

Introduction: When running hybrid database environments, you often need to query some data from a remote db of any type, while being connected to your MS SQL Server database. Problems start when you try to combine that with some "user input" pass…
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…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

743 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

16 Experts available now in Live!

Get 1:1 Help Now