Wrox Programmer Forums
|
SQL Server 2005 General discussion of SQL Server *2005* version only.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the SQL Server 2005 section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old October 9th, 2009, 12:50 PM
Friend of Wrox
 
Join Date: Jun 2003
Posts: 196
Thanks: 0
Thanked 0 Times in 0 Posts
Default test for temporary tables

I use a lot of temporary tables in my scripts - tables like #tablename.

When I rerun the script, I get error messages that they already exist.

I have tried doing a
Code:
DROP TABLE #tablename
I then get an error message that they do not exist.

How can I test for the existence of the temporary tables before doing the DROP TABLE command?

All the code I've seen so far only works for permanent tables.
__________________
Rand
 
Old October 9th, 2009, 01:05 PM
Friend of Wrox
 
Join Date: Jun 2003
Posts: 196
Thanks: 0
Thanked 0 Times in 0 Posts
Default Answer

I just figured it out:

Code:
IF OBJECT_ID (N'tempdb..#tablename', N'U') IS NOT NULL
BEGIN
    DROP TABLE #tablename
END
The "tempdb.." seems to be the key to the answer.
__________________
Rand
 
Old October 9th, 2009, 01:06 PM
Friend of Wrox
 
Join Date: May 2004
Posts: 642
Thanks: 0
Thanked 43 Times in 42 Posts
Default

You can do something like:
Code:
--Create table
USE Norhtwind
GO

CREATE TABLE #temp(id INT)

--Check if it exists
IF OBJECT_ID('tempdb..#temp') IS NOT NULL
BEGIN
PRINT '#temp exists!'
END
ELSE
BEGIN
PRINT '#temp does not exist!'
END
Please check the following URL for more details:

http://weblogs.asp.net/jnadal/archiv...24/438960.aspx
http://sqlservercodebook.blogspot.co...le-exists.html
__________________
Om Prakash Pant
Click the "Thanks" button if this post helped you.





Similar Threads
Thread Thread Starter Forum Replies Last Post
Temporary Tables Challenge! PCNHSL PHP How-To 1 November 8th, 2007 09:42 AM
creating temporary tables instead of queries clwk Access VBA 4 March 12th, 2007 02:50 PM
Temporary tables eadred ADO.NET 4 August 8th, 2005 12:49 AM
Sql Server Temporary Tables itHighway SQL Server 2000 1 July 14th, 2005 12:33 AM
Urgent Help : XML to Sql temporary tables Milan XML 2 November 6th, 2004 07:36 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.