Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter based on an aliased column name

I'm using SqlServer 2005 and I have a column that I named.

The query is something like:

SELECT id, CASE WHEN <snip extensive column definition> END AS myAlias
FROM myTable
WHERE myAlias IS NOT NULL

However, this gives me the error:

"Invalid column name 'myAlias'."

Is there a way to get around this? In the past I've included the column definition in either the WHERE or the HAVING section, but those were mostly simple, IE COUNT(*) or whatever. I can include the whole column definition in this ad-hoc query, but if for some reason I needed to do this in a production query I'd prefer to have the column definition only once so I don't have to update both (and forget to do one at some point)

like image 393
Nathan Koop Avatar asked Feb 22 '10 14:02

Nathan Koop


2 Answers

You can't reference aliases in a where clause like that... you either have to duplicate the CASE in the WHERE, or you can use a subquery like this:

SELECT id, myAlias
FROM
(
    SELECT id, CASE WHEN <snip extensive column definition> END AS myAlias
    FROM myTable
) data
WHERE myAlias IS NOT NULL
like image 183
Michael Bray Avatar answered Oct 13 '22 07:10

Michael Bray


Using CTEs is also an option:

;with cte (id, myAlias)
 as (select id, case when <snip extensive column definition> end as myAlias 
      from myTable)
 select id, myAlias
  from cte
  where myAlias is not null
like image 23
Philip Kelley Avatar answered Oct 13 '22 07:10

Philip Kelley