title: SQL query runs 10 times slower with certain value when using variable
body: <p><strong>EDIT</strong>: No result in <code>DB1.dbo.TABLE_B</code> with <code>STRING_ID ='id009'</code> or <code>'id008'</code>; <code>STRING_ID</code> is <code>varchar(100)</code> and is not unique.</p>
  
  <p><strong>EDIT2</strong>: Execution plan for both queries are same.</p>
  
  <p>I have a query below running on a SQL Server 2008 server:</p>
  
  <pre><code>DECLARE @stringid nvarchar(10)
  SET @stringid='id009'
  SELECT * FROM DB1.dbo.TABLE_A
           INNER JOIN DB1.dbo.TABLE_B
           ON DB1.dbo.TABLE_A.ID=DB1.dbo.TABLE_B.ID
  WHERE DB1.dbo.TABLE_B.STRING_ID=@stringid
  ORDER BY DB1.dbo.TABLE_B.UID desc, DB1.dbo.TABLE_A.TIME desc 
  </code></pre>
  
  <p>This query will take 10 seconds to get the result (which is empty).</p>
  
  <p>If I change the second line of this query to use any other value e.g. </p>
  
  <pre><code>SET @stringid='id008'
  </code></pre>
  
  <p>The query will get the result instantly (empty result as well).      </p>
  
  <p><strong>More importantly:</strong> If I change the query to not use the variable but just pass the value ('id009') as below:</p>
  
  <pre><code>SELECT * FROM DB1.dbo.TABLE_A
           INNER JOIN DB1.dbo.TABLE_B
           ON DB1.dbo.TABLE_A.ID=DB1.dbo.TABLE_B.ID
  WHERE DB1.dbo.TABLE_B.STRING_ID='id009'
  ORDER BY DB1.dbo.TABLE_B.UID desc, DB1.dbo.TABLE_A.TIME desc
  </code></pre>
  
  <p>The query will also get the result instantly (empty result).</p>
  
  <p>So my question is why is this query running so slow with variable set to that certain value? </p>