Note that there are some explanatory texts on larger screens.

plurals
  1. POnested SELECT statements interact in ways that I don't understand
    text
    copied!<p>I thought I understood how I can do a <code>SELECT</code> from the results of another <code>SELECT</code> statement, but there seems to be some sort of blurring of scope that I don't understand. I am using SQL Server 2008R2.</p> <p>It is easiest to explain with an example.</p> <p>Create a table with a single nvarchar column - load the table with a single text value and a couple of numbers:</p> <pre><code>CREATE TABLE #temptable( a nvarchar(30) ); INSERT INTO #temptable( a ) VALUES('apple'); INSERT INTO #temptable( a ) VALUES(1); INSERT INTO #temptable( a ) VALUES(2); select * from #temptable; </code></pre> <p>This will return: <code>apple, 1, 2</code> </p> <p>Use <code>IsNumeric</code> to get only the rows of the table that can be cast to numeric - this will leave the text value <code>apple</code> behind. This works fine.</p> <pre><code> select cast(a as int) as NumA from #temptable where IsNumeric(a) = 1 ; </code></pre> <p>This returns: <code>1, 2</code></p> <p>However, if I use that exact same query as an inner select, and try to do a numeric <code>WHERE</code> clause, it fails saying cannot convert <code>nvarchar</code> value 'apple' to data type <code>int</code>. How has it got the value 'apple' back??</p> <pre><code> select x.NumA from ( select cast(a as int) as NumA from #temptable where IsNumeric(a) = 1 ) x where x.NumA &gt; 1 ; </code></pre> <p>Note that the failing query works just fine without the <code>WHERE</code> clause:</p> <pre><code> select x.NumA from ( select cast(a as int) as NumA from #temptable where IsNumeric(a) = 1 ) x ; </code></pre> <p>I find this very surprising. What am I not getting? TIA</p>
 

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