Tuesday, March 27, 2012

Aliased Column and Where Clauses

I want to use an aliased field with a where caluse as below

select member_ID,
CASE
WHEN (status_id & (16 | 128)) = (16 | 128) OR (status_id & 16 ) = 0
THEN CAST(1 AS bit) ELSE CAST(0 AS bit)
END AS IsMigrated
FROM member
LEFT OUTER JOIN language ON language.language_id = member.country_id
WHERE language = 'Deutsch'
-- AND IsMigrated = 1

However i keep getting "Invalid column name 'IsMigrated'" when i uncomment the AND IsMigrated = 1 line.

That construct is not available in TSQL; you will need to either need to convert that into a function or "spell it out fully" in the where clause.

Here are a few past threads that had related discussions:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=89097&SiteID=1
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1137002&SiteID=1
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=803299&SiteID=1

|||

You could try using a derived table, see below.

Chris

Code Snippet

SELECT t.member_ID,

t.IsMigrated

FROM (

SELECT member_ID,

CASE WHEN (status_id & (16 | 128)) = (16 | 128)

OR (status_id & 16) = 0 THEN CAST(1 AS BIT)

ELSE CAST(0 AS BIT)

END AS IsMigrated

FROM member

LEFT OUTER JOIN language ON language.language_id = member.country_id

WHERE language = 'Deutsch'

) t

WHERE t.IsMigrated = 1

|||

The data behind an 'aliased' column is not known by that alias during the data retreival. You cannot use an 'aliased' column name in the SELECT, JOIN conditions, or WHERE criteria of a query.

However, since the data from the query is 'pulled' into a derived table and then sorted, the derived table will know the 'aliased' data by the column name aliases, and you can use the alias in the ORDER BY

|||

I just keep running into this one...

A question to the developement team of SQL: is there any reason why this hasn't been implemented?

The simplest implementation would be to sunbstitue any reference to a derived column with it's definition, by doing a search & replace on the code before feeding it to the interpreter. I can't figure out why it would be difficult to implement or how it would break existing code.

Simple thing like

Col1+Col2 as Sub1,

col3 + col4 as Sub2,

Sub1 + Sub2 as Total

Shouldn't be too hard for the interpreter to figure out? (Access can do it...)

Also something like

select Col1 + '.' + Col2 as Concat,

... bla bla

Group by Concat

Order by Concat

This would really help to keep your 'eye on the ball' instead of on the technical implementation. It would also help maintainability.

So..... next CTP of Katmai it is then? ;-)

Regards,

Gert-Jan

|||

Post your suggestions at:

Suggestions for SQL Server

http://connect.microsoft.com/sqlserver

No comments:

Post a Comment