sql server - MS SQL: Nested Selects - Mysterious "Invalid column name" error -


when run following query against mssql 2000

select      distinct(email),     (select top 1 activityid         activity aa, activitytype tt          aa.activitytypeid = tt.activitytypeid              , aa.consumerid = c.consumerid             , tt.activitytype = 'something_optin') optin,     (select top 1 activityid         activity aa, activitytype tt          aa.activitytypeid = tt.activitytypeid              , aa.consumerid = c.consumerid             , tt.activitytype = 'something_optout') optout     activity a,     consumer c,     activitytype t     c.countryid = '23'     , t.activitytype = 'something_create'     , a.activitytypeid = t.activitytypeid     , c.consumerid = a.consumerid     , optin > 1 

i following error

server: msg 207, level 16, state 3, line 1 invalid column name 'optin'. 

why happen? can't see why invalid.

sql server not allow refer aliases name @ same level. fix this, repeat column definition:

where     c.countryid = '23'     , t.activitytype = 'something_create'     , a.activitytypeid = t.activitytypeid     , c.consumerid = a.consumerid     , (select top 1 activityid         activity aa, activitytype tt          aa.activitytypeid = tt.activitytypeid              , aa.consumerid = c.consumerid             , tt.activitytype = 'something_optin'         ) > 1 

or use subquery:

select  *    (         select              distinct(email),             (...) optin,             (...) optout                     activity a,             consumer c,             activitytype t         ) subqueryalias     c.countryid = '23'     , t.activitytype = 'something_create'     , a.activitytypeid = t.activitytypeid     , c.consumerid = a.consumerid     , optin > 1 

Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -