sql server - T-SQL: Can a subquery in the SELECT clause implicitly reference a table in the main outer query? -


in t-sql, possible have subquery in select clause implicitly references tables in main, outer query? example:

select name,        case when exists (select o.orderid) 1 else 0 end buyer   customer c   left join order o     on c.custid = o.custid 

in other words, can write subqueries without clause?

intellisense seems recognize outer table aliases in subqueries, can't find documentation says acceptable t-sql. can run of own tests, wanted check community. thanks.

yes valid syntax.

a select without from treated though selecting single row table. referencing columns outer query required correlated sub queries , valid there.

the particular query have makes no sense though. evaluate 1 subquery returns single row (with single column containing corresponding o.orderid) going exists check.

probably want check o.orderid null

select name,         case           when o.orderid null 0           else 1         end buyer,    customer c         left join order o                on c.custid = o.custid  

where make sense use type of syntax in null safe equality check.

e.g.

select a,         b,         case           when exists (select t.a                        except                        select t.b) 1           else 0         end distinctfrom    t  

is equivalent

select a,         b,         case           when <> b                 or ( null                      , b not null )                 or ( not null                      , b null ) 1           else 0         end distinctfrom    t  

Comments

Popular posts from this blog

rdbms - what exactly the undo information lives in oracle? -

bash - How do you programmatically add a bats test? -

clojure - 'get' replacement that throws exception on not found? -