HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Where clause for aliased column

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
columnaliasedwhereforclause

Problem

I have a query which parses a string values from a column:

SELECT left(DateTimeSent, 17) AS timesent FROM allog_07_11_e query1


When I do:

SELECT left(DateTimeSent, 17) AS timesent FROM allog_07_11_e query1.timesent != '0'


I get:

Msg 207, Level 16, State 1, Line 1
Invalid column name 'timesent'.


Any ideas why?

Solution

You can't reference an alias in the WHERE clause. You'd have to do something like this:

select left(DateTimeSent, 17) as timesent
from allog_07_11_e
where left(DateTimeSent, 17) <> '0'


Likewise, you could also use a subquery:

select *
from
(
    select left(DateTimeSent, 17) as timesent
    from allog_07_11_e
) a
where timesent <> '0'

Code Snippets

select left(DateTimeSent, 17) as timesent
from allog_07_11_e
where left(DateTimeSent, 17) <> '0'
select *
from
(
    select left(DateTimeSent, 17) as timesent
    from allog_07_11_e
) a
where timesent <> '0'

Context

StackExchange Database Administrators Q#17962, answer score: 5

Revisions (0)

No revisions yet.