Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can't easily control the way SQL Server processes your query. You can figure out some of the why by deep diving into the execution plan, but understanding that is the least of your problems in this specific case I think. You can do a little with join hints, perhaps, but that's hacky to me and the behavior is still not guaranteed (especially as you move to new versions etc). Two workarounds you could try are:</p> <pre><code>;WITH c AS ( SELECT varcharColumn, ParentID, TypeId FROM dbo.Child AS c WHERE c.TypeId = 2 AND ISNUMERIC(varcharColumn) = 1 --* ) SELECT CONVERT(INT, c.varcharColumn) FROM dbo.Parent AS p INNER JOIN c ON c.ParentId = p.Id WHERE p.TypeId = 13; </code></pre> <p>But I have heard of cases where even separating this out into a CTE could lead to the bad plan that led the convert to occur first. So it may be that you need to break it out even further:</p> <pre><code>SELECT varcharColumn, ParentID, TypeId INTO #c FROM dbo.Child AS c WHERE c.TypeId = 2 AND ISNUMERIC(varcharColumn) = 1; --* SELECT CONVERT(INT, c.varcharColumn) FROM dbo.Parent AS p INNER JOIN #c AS c ON c.ParentId = p.Id WHERE p.TypeId = 13; </code></pre> <p>(I also talk about the <code>CASE</code> expression solution in <a href="https://stackoverflow.com/a/21316088/61305">this answer</a>.)</p> <p>If you are on SQL Server 2012, you can simply do this - now it doesn't matter if the convert is attempted before the filter, and you don't have to rely on the wonky <code>ISNUMERIC()</code> function.*</p> <pre><code>SELECT TRY_CONVERT(INT, c.varcharColumn) FROM dbo.Parent AS p INNER JOIN dbo.Child AS c ON c.ParentId = p.Id WHERE c.TypeId = 2 AND p.TypeId = 13; </code></pre> <p><code>*</code> Please note that IsNumeric is not perfect. I wrote this article several years ago to help deal with this: <a href="http://classicasp.aspfaq.com/general/what-is-wrong-with-isnumeric.html" rel="nofollow noreferrer">http://classicasp.aspfaq.com/general/what-is-wrong-with-isnumeric.html</a></p>
    singulars
    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.
    1. This table or related slice is empty.
    1. VO
      singulars
      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