title: SQL error - Must declare the table variable "@tablename"
body: <p>How to create variable inside in function and select data from table?
  When I tried to create this function I get error:</p>
  
  <blockquote>
    <p>Must declare the table variable "@tablename"</p>
  </blockquote>
  
  <p>this is my function:</p>
  
  <pre><code>create function FunctionName (@val1 INT , @val2 INT)
  
  RETURNS @result TABLE
  (
  Name1 nvarchar(100) not null,
  Name2 nvarchar(100) not null,
  Name3 nvarchar(100) not null,
  Name4 nvarchar(100) not null,
  )
  
  AS
  BEGIN
      DECLARE @tablename nvarchar(max)
      SET @tablename = CONCAT('Export_Pivot_',@val1,'_',@val2)    
      INSERT into @result
  SELECT 
  name1,name2,name3,name4
  FROM  @tablename
  
  RETURN
  END
  </code></pre>