title: Dynamic SQL Replacement Requires Whitespace
body: <p>I have a dynamic SQL stored procedure that should replace certain parameters in the query below. However, it seems like parameters don't get replaced unless they have whitespace on both sides. Are there some escape characters or delimiters I can use to indicate the start and end of a parameter-name?</p>
  
  <p>@phi_min and @phi_max are replaced just fine, but not @server or @sim_id.</p>
  
  <pre><code>DECLARE @query NVARCHAR(500) = 
    N'SELECT  COUNT(*)
      FROM    [@server].[someDatabaseName].[dbo].[TableName_@sim_id]
      WHERE   @phi_min &lt;= phi AND phi &lt; @phi_max'
  
  
  DECLARE @paramDefinition NVARCHAR(500) = 
    N'@server         nvarchar(20),
      @sim_id         int,
      @phi_min        real,
      @phi_max        real'
  
  Execute sp_Executesql @query, @paramDefinition,
          @server, 
          @sim_id,
          @phi_min,
          @phi_max,
  </code></pre>
  
  <p>A poor solution is to replace:</p>
  
  <pre><code>FROM    [@server].[databaseName].[dbo].[TableName_@sim_id]
  </code></pre>
  
  <p>with:</p>
  
  <pre><code>FROM    '+QUOTENAME(@server)+'.[ggDxgg-700].[dbo].[PhiPsi_' + CAST(@sim_id as NVARCHAR(500))+ ']
  </code></pre>
  
  <p>but this skirts the type-checking safety that sp_executesql is supposed to provide when one passes the query, parameter-definitions, and parameter-values separately.</p>