简体   繁体   中英

Assigning a select statement inside of a where clause

I'd like to know if it's legal to do this?

select coalesce(myField, (select myfield2 from table1))
from table2

I've been trying to get this statement to work for hours:

 select 
 coalesce( a.TransactionCurrencyId,

            (
            select c.TransactionCurrencyId
            from CRM_accountbase c
            join crm_pricelevelbase a
            on c.defaultpricelevelid=a.pricelevelid
            where a.pricelevelid=(
                            select a.DefaultPriceLevelId 
                            from
                                 (
                                     select a.DefaultPriceLevelId,c.iCompanyId
                                     from crm_accountbase a
                                     join onyx..company C
                                     on c.iCompanyId=a.accountnumber
                                 ) a
                                 where a.iCompanyId=c.iCompanyId
                                 ) 
            ) TransactionCurrencyId
 from mytable a

The problem is not with the logic. It is with the syntax.

Is it OK to have a select statement inside of a coalesce and another select statement inside of a where condition?

Yes, it's ok to have a select inside of coalesce and inside of a where statement (assuming they return only a single row if you're comparing equality).

See my inline comments near the bottom of the code.

Also, it isn't a syntax problem, but it would be a good idea to not alias three different tables as 'a'.

select 
 coalesce( a.TransactionCurrencyId,
            (
                 select c.TransactionCurrencyId
                 from CRM_accountbase c
                 join crm_pricelevelbase a
                 on c.defaultpricelevelid=a.pricelevelid
                 where a.pricelevelid=(
                            select a.DefaultPriceLevelId 
                            from
                                 (
                                     select a.DefaultPriceLevelId,c.iCompanyId
                                     from crm_accountbase a
                                     join onyx..company C
                                     on c.iCompanyId=a.accountnumber
                                 ) a 
                              where a.iCompanyId=c.iCompanyId
                              ) 
            ) --TransactionCurrencyId   <--Need to not alias the subquery here
          )  --< Need to add this parenthesis
 from mytable a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM