Search code examples
sql-servert-sqlsubquerycorrelated-subquery

Why correlated subquery doesn't allow two expressions - SQL Server


I have query like this:

select 
    objectid,
    (select top 1 data_source, maxspeed
     from SpeedLimitData3
     where way_geometry.Filter(geography::STGeomFromText('POINT (' + cast(X as varchar(15)) + ' ' + cast(Y as varchar(15)) + ')', 4326)) = 1
     order by way_geometry.STDistance(geography::STGeomFromText('POINT (' + cast(X as varchar(15)) + ' ' + cast(Y as varchar(15)) + ')', 4326))
    )
from 
    testData

Why does the SQL Server throw this error?

Msg 116, Level 16, State 1, Line 8
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

I know that this means that I need to remove one of subquery's selected columns. But why when I have single row as subquery result and not several?


Solution

  • The syntax of a select clause in Transact-SQL allows a <select-list> made up of various entities. A correlated subquery used in a select clause is an expression and supplies the value for a single result column.