tags:

views:

172

answers:

8

I wounder how I could use an alias in a where statement.

Example :

SELECT SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3)  AS Col1
FROM MyTable
WHERE Col1 = 'MySearch'

I use MSSQL 2005

A: 

I think it is not possible, but maybe you can take a look on Common Table Expressions over SQL 2005

Like this:

WITH MyCTE( Col1) AS
(
SELECT SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3)  AS Col1
FROM MyTable
)
SELECT *
FROM MyCTE
WHERE Col1 = 'MySearch'
Jhonny D. Cano -Leftware-
A: 
SELECT * FROM (
  SELECT SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3)  AS Col1
  FROM MyTable
)
WHERE Col1 = 'MySearch'

(I know this works in Oracle, I believe it is standard SQL and would work in MSSQL.)

Dave Costa
It's likely to be slower though, if the inner query becomes complex.
Joel Coehoorn
+1  A: 

Use a subquery:

SELECT * 
FROM 
  (SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3) AS Col1 FROM MyTable)
WHERE Col1 = 'MySearch'
altCognito
+2  A: 

Not possible, but you can do the following:

SELECT SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3)  AS Col1
FROM MyTable
WHERE SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3) = 'MySearch'

No subqueries or hacks required

David Caunt
A: 

use a view or a derived table.

Using a derived table, your example would look like:

select col1 
from 
(SELECT SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3)  AS Col1
FROM MyTable) 
where col1='Mysearch'
JMM
A: 

The answer is you can't - you can do this

SELECT 
    SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3)  AS Col1
FROM 
    MyTable
WHERE 
    SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3) = 'MySearch'
Russ Cam
A: 

Actually, using alias won't make your query any faster as SQL optimizer is not as dumb as you think, so I'd just repeat the SUBSTRING expression again.

zvolkov
For me, He is looking a way for doing the query's more readable
Jhonny D. Cano -Leftware-
That's a bit a violation of the DRY principle, isn't it ? When you modify the select clause, you've to make sure to modify the WHERE as well ...
Frederik Gheysels
Adding a subquery or using Having will make the query more complex which is worse that repeating such a simple expression twice.
zvolkov
A: 

You can do this:

SELECT Col1
FROM ( SELECT SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3) AS Col1 ) AS x
WHERE Col1 = 'MySearch'
Frederik Gheysels