title: Msg 1087, Level 16, State 1, Line 25 Must declare the table variable
body: <p>I am creating a stored procedure and in it I am creating a new table that appends two variables, an ID and getdate() to the table name when it is create.  i.e tablename_@id_getdate(). So the table name will change depending on which id and on what date it is run. I am doing this with Dynamic SQL. Then after the table is created, I need to insert records to it from a temp table created earlier in the procedure.(not shown).  Since I won't know the name of the table until it is created, I am trying to insert into using the @tablename variable.</p>
  
  <p>I've tried the below script and am getting this error: 
  Msg 1087, Level 16, State 1, Line 25
  Must declare the table variable "@TABLENAME".</p>
  
  <p>This procedure will run every other day or so and the affected records of the run will be stored in the tablename_@id_getdate() table created during the execution of the stored procedure.</p>
  
  <p>Is there another way of doing this or is my syntax just wrong?  Thanks for your help.  </p>
  
  <pre><code>IF EXISTS (SELECT 1 FROM #DUPS2)
  BEGIN
  
  DECLARE @TableName NVARCHAR(128)
  DECLARE @SQLString NVARCHAR(MAX)
      ,@DATE VARCHAR (10)
      ,@BN SMALLINT
  
  SET @BN = 108       
  SET @DATE = CONVERT(VARCHAR(10),GETDATE(),112)
  
  SET @TABLENAME = 'schema.dbo.tableName_' + CAST (@BN AS VARCHAR) +'_'+ @DATE 
  
  SET @SQLString = 'CREATE TABLE '+' '+@TABLENAME+ ' '
          + '( ' + 'BUSINESS_NAME' + ' ' +'VARCHAR(120)' +' '+'NULL,' +
               'CLAIM_ID' + ' ' +'NVARCHAR(120)' +' '+'NULL,' + 
               'CONTACT_ID' + ' ' +'INT' +' '+'NULL,' +
               'COUNT_OF_DUPES' + ' ' +'NVARCHAR(5)' +' '+'NULL' +') ON     [PRIMARY] '
  
  
  EXEC @SQLString
  
  ---TABLE IS CREATED AND NOW WE INSERT RECORDS TO IT
  
  INSERT INTO @TABLENAME  --the table name just created.
  SELECT D.*  
  FROM #DUPS2 D     --contains duplicate contact records found
   JOIN TABLE1  T1 WITH (NOLOCK)
   ON D.CONTACT_ID = T1.CONTACT_ID
  WHERE T1. active_ind = 1 
  
  END
  </code></pre>