title: How to pass a table variable using sp_executesql
body: <p>I'm trying to create a table using sp_executesql but I keep getting an error that says "Incorrect syntax near '@_TableName'.  Any idea what I'm doing wrong here?</p>
  
  <p>Here's the code that I'm using:</p>
  
  <pre><code>DECLARE @SQLString NVARCHAR(MAX), 
          @ParamDefinition NVARCHAR(MAX), 
          @TableName NVARCHAR(MAX);
  
  SET @TableName  = N'[dbo].[MyTable]';
  
  SET @SQLString = N'SELECT * FROM @_TableName;';
  
  SET @ParamDefinition = N'@_TableName NVARCHAR(max)';
  
  EXEC sp_executesql @SQLString, @ParamDefinition, 
                     @_TableName = @TableName;
  </code></pre>
  
  <p>That yields the error:</p>
  
  <pre><code>Msg 102, Level 15, State 1, Line 1
  Incorrect syntax near '@_TableName'.
  </code></pre>
  
  <p>If I hard code the table name and the column type (I have to do both) then the query works, otherwise I get the incorrect syntax message for both those variables.</p>
  
  <p>In case you're wondering, I want to put this code inside a stored procedure, so that if anyone wants to create or modify a table then they call this stored procedure which can run additional validations.</p>