SQL Use alias in Where statement

前端 未结 10 1224
南笙
南笙 2020-11-29 06:09

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
W         


        
相关标签:
10条回答
  • 2020-11-29 06:53

    You can use "having" instead of "where".

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

    Having do a "where" after execution of the query. Be careful to use it in the right conditions to have no performance problem.

    0 讨论(0)
  • 2020-11-29 06:53

    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.

    0 讨论(0)
  • 2020-11-29 06:54

    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'
    
    0 讨论(0)
  • 2020-11-29 06:59
    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.)

    0 讨论(0)
提交回复
热议问题