title: Initializing table name to be used in a stored procedure in SQL Server
body: <p>I am trying to create a stored procedure to achieve the following in the stored procedure</p>
  
  <pre><code>DECLARE @TBLNAME VARCHAR(128)
  
  SET @TBLNAME = SELECT PAR_VALUE FROM DBO.PARAMETERS WHERE PAR_NAME='SALES_ORDERS_TABLE';
  </code></pre>
  
  <p>The <code>PAR_VALUE</code> column in the <code>PARAMETERS</code> table contains the name of the table of the <code>Sales Order</code> table.</p>
  
  <p>I now want to use this table name in the stored procedure, and count the number of rows in this table.</p>
  
  <pre><code>DECLARE @SQL NVARCHAR(4000)
  @ SQL = SELECT COUNT(*) FROM '[@TBLNAME]'
  </code></pre>
  
  <p>However, when I try to run this, there are multiple errors. </p>
  
  <p>Can you please help me by guiding on how to do this?</p>
  
  <p>I just now tried this code:</p>
  
  <pre><code>CREATE PROCEDURE JCOUNT_SO
  AS
  DECLARE @TBLNAME NVARCHAR(512)
  SELECT @TBLNAME=(SELECT PAR_VALUE FROM DBO.PARAMETERS WHERE PAR_NAME='SALES_ORDERS_TABLE')
  
  DECLARE @SQL NVARCHAR(4000)
  SELECT @SQL='SELECT COUNT(*) AS #_OF_RECORDS INTO SO_COUNT
  FROM' '+QUOTENAME(@TBLNAME)''
  
  EXEC SP_EXECUTESQL @SQL;
  </code></pre>
  
  <p><strong>Error Message: Invalid Object Name: 'TEST.DBO.SO_MASTER'</strong> </p>
  
  <p>Please help on this code. </p>