Cogslave Cogslave - 10 months ago 46
SQL Question

Scope of temporary tables in SQL Server 2012

I wrote a stored procedure to import & transform data from one database to another.

Each import would take a single company id and import all data related to this company.

To help with the transformation step I use temporary tables.

As part of the script review and I was told to use table variables rather than temporary tables.
This is because if we ran two different imports at the same time, the temporary table would be shared and corrupt the import.

Is this true?
I thought each call to EXEC created a new scope?

Here is a contrived example of the script.

CREATEPROC [dbo].[ImportCompany]
EXEC [dbo].[ImportAddress] @CompanyId = @CompanyId
--Import other data

CREATE PROC [dbo].[ImportAddress]
CREATE TABLE #Companies (OldAddress NVARCHAR(128), NewAddress NVARCHAR(128))
INSERT INTO #Companies(OldAddress, NewAddress)
Address as OldAddress,
'Transformed ' + Address as NewAddress
CompanyId = @CompanyId

--Do stuff with the transformed data

DROP TABLE #Companies

EXEC [dbo].[ImportCompany] @CompanyId = 12345



Local temporary tables are visible only in the current session

and (more importantly):

If a local temporary table is created in a stored procedure or application that can be executed at the same time by several users, the Database Engine must be able to distinguish the tables created by the different users. The Database Engine does this by internally appending a numeric suffix to each local temporary table name.

Which exactly rebuts the point of whoever said that they would be shared.

Also, there's no need to DROP TABLE at the end of your procedure (from same link again):

A local temporary table created in a stored procedure is dropped automatically when the stored procedure is finished