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
What you want is called Dynamic SQL.
First, create the statement inside a VARCHAR:
Then, execute the statement via
sp_executesql:Creating the table goes in the same way: