Avoiding Global temporary table problems between databases

No.of Views1247
Bookmarked0 times
Downloads 
Votes0
By  ayyanarj   On  16 Feb 2010 03:02:22
Tag : Sql Servers , Database Administrator
Avoiding Global temporary table problems between databases
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

 Global temp tables are used to store values that can be used across the stored procedures in particular application run. it will disappears when application is stopped.

Global temp tables are created by following query.

CREATE TABLE [dbo].[##Temp] (ID INT)


if global temp tables are created and used by single instance only, problem(creating 2 temp table with same name) will not occur. The problem will occur when another instance creating same temp table at same time. This problem will occur on same database or another database with same name of temp table creation.

To avoid this confliction, we will use GUID with temp table name. But this method is more constlier and difficult to handle. Because temp table name is so lengthy.
 

EXEC ( 'CREATE TABLE [dbo].[##Temp' + CONVERT(VARCHAR, NEWID()) + ' ] (ID INT)' )


Otherwise we can use identity value of some table with temp table name.

EXEC ( 'CREATE TABLE [dbo].[##Temp' + @ID + ' ] (ID INT)' )


The above method will solve the problem even multiple instances running on same database. Because each instance will create unique identity value and using that id with temp table name.

Again problem will occur between different databases creating the same temp table with same identity value. This problem will occur when the multiple instance running on different databases at the same time. Because each instance trying to create temp table with same name.

To avoid confliction between different databases, use DB_ID() or DB_NAME() with temp table name.

EXEC ( 'CREATE TABLE [dbo].[##Temp' + CONVERT(VARCHAR, DB_ID()) + @ID + ' ] (ID INT)' )

EXEC ( 'CREATE TABLE [dbo].[##Temp' + CONVERT(VARCHAR, DB_NAME()) + @ID + ' ] (ID INT)' )


Because DB_ID() or DB_NAME() will be unique to each database.

 
Sign Up to vote for this article
 
About Author
 
ayyanarj
Occupation-Software Engineer
Company-Effindi Technologies Private Limited
Member Type-Junior
Location-India
Joined date-04 Aug 2009
Home Page-http://ayyanar.blogspot.com
Blog Page-http://ayyanar.blogspot.com
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top