Note that there are some explanatory texts on larger screens.

plurals
  1. POCommon Table Expressions slow when using a table variable
    primarykey
    data
    text
    <p>I have been experimenting with the following (simplified) CTE. When using a table variable () the query runs for minutes before I cancel it. Any of the other commented out methods return in less than a second. </p> <p>If I replace the whole WHERE clause with an INNER JOIN it is fast as well. </p> <p>Any ideas why using a table variable would run so slowly?</p> <p>FWIW: The database contains 2.5 million records and the inner query returns 2 records. </p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE #rootTempTable (RootID int PRIMARY KEY) INSERT INTO #rootTempTable VALUES (1360); DECLARE @rootTableVar TABLE (RootID int PRIMARY KEY); INSERT INTO @rootTableVar VALUES (1360); WITH My_CTE AS ( SELECT ROW_NUMBER() OVER(ORDER BY d.DocumentID) rownum, d.DocumentID, d.Title FROM [Document] d WHERE d.LocationID IN ( SELECT LocationID FROM Location JOIN @rootTableVar rtv ON Location.RootID = rtv.RootID -- VERY SLOW! --JOIN #rootTempTable tt ON Location.RootID = tt.RootID -- Fast --JOIN (SELECT 1360 as RootID) AS rt ON Location.RootID = rt.RootID -- Fast --WHERE RootID = 1360 -- Fast ) ) SELECT * FROM My_CTE WHERE (rownum &gt; 0) AND (rownum &lt;= 100) ORDER BY rownum </code></pre> <p>This is from when using the table variable. The query took over 17 minutes to run: <img src="https://i.stack.imgur.com/ZJXzP.png" alt="enter image description here"></p> <p><strong>Execution plans in XML format</strong></p> <p>Temp table: <a href="https://docs.google.com/open?id=0B66I-fxlyEtEZEthV3ZaWlNLWXM" rel="nofollow noreferrer">https://docs.google.com/open?id=0B66I-fxlyEtEZEthV3ZaWlNLWXM</a></p> <p>Table variable: <a href="https://docs.google.com/open?id=0B66I-fxlyEtEbUFZa3RJejFCTkk" rel="nofollow noreferrer">https://docs.google.com/open?id=0B66I-fxlyEtEbUFZa3RJejFCTkk</a></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload