Imsopov
Imsopov

Reputation: 155

Create temporary table from variable in stored procedure

I am trying to figure out how to create a temporary table that is created using a variable passed into the stored procedure, I know you can concatenate using + when it is in quotes (as seen in the check if the table exists below) but is it possible for me to generate a temp table using a variable as there are multiple agents who will be using this and I have to make sure the table is unique in case it is ran at the same time.

CREATE PROCEDURE TP_Getagentcdr @agentid VARCHAR(20), @date VARCHAR(20) ,@enddate VARCHAR(20)

AS
BEGIN
  IF OBJECT_ID('databasename.'+@agentid+'Tempcdr') IS NOT NULL  
    DROP TABLE databasename.+@agentid+Tempcdr

  CREATE TABLE databasename.@agentid+Tempcdr
END

Upvotes: 0

Views: 2258

Answers (1)

vstrien
vstrien

Reputation: 2605

What you want is called Dynamic SQL.

First, create the statement inside a VARCHAR:

DECLARE @drop_statement VARCHAR(MAX) = 'DROP TABLE databasename.' + @agentid + 'Tempcdr'

Then, execute the statement via sp_executesql:

sp_executesql @drop_statement

Creating the table goes in the same way:

DECLARE @create_statement VARCHAR(MAX) = 'CREATE TABLE databasename.' + @agentid + 'Tempcdr'

sp_executesql @create_statement

Upvotes: 2

Related Questions