Shah
Shah

Reputation: 1654

is there any issue when creating two temporary tables in one stored procedure

I have written below stored procedure. In which i need to create Two Temporary Tables. On first temporary table i am taking id's using cursors and then based on some query need to insert in 2nd temporary table. But i get the below error. . I need some assistance over this situation

There is already an object named 'TempTable' in the database.

ALTER PROCEDURE [dbo].[GetDocumentByTrackID]

@idList nvarchar(50)

AS
BEGIN

SET NOCOUNT ON;
DECLARE @TrackId INT

--Temprary Table 1

CREATE TABLE TempTable(
ID INT
)

DECLARE @GetNextRecord cursor
INSERT INTO TempTable SELECT Value from dbo.fn_sqllist_to_table(@idList,';')

--Temprary Table 2

Create TABLE TracksNameID
(
ID INT,
Name nvarchar(100)
)

SET @GetNextRecord = cursor for select ID from TempTable

open @GetNextRecord
FETCH FROM @GetNextRecord into @TrackId
while @@FETCH_STATUS = 0
BEGIN
INSERT INTO TracksNameID
SELECT  ID ,Name FROM  dbo.TestTable 
WHERE   dbo.TestTable.TrackID = @TrackId
END
FETCH FROM @GetNextRecord into @TrackId
DROP TABLE TempTable
END

Upvotes: 0

Views: 562

Answers (2)

Matten
Matten

Reputation: 17631

These aren't actually temporary tables, you're creating real table objects. If the stored procedure fails somewhere, the tables won't be removed. Better stick with table variables:

DECLARE @tableName TABLE (
  id int, ... )

and use @tableName like a table (which it is). This way everything will be bound to the local scope of the stored procedure.

The drawback of table variables over temporary tables are the lack of clustered indexes and you can't ALTER table variables.

Upvotes: 2

Oleg Dok
Oleg Dok

Reputation: 21766

You creating regular tables, temp table names should begin with #

Try to create #TempTable and #TracksNameID

Upvotes: 1

Related Questions