Where子句基于函数的值

时间:2015-08-10 23:36:33

标签: sql sql-server tsql

我有一个SQL Server函数,它将一些数据组合起来输出地址

dbo.pt_FormatAddress(
    Permit_Address.Permit_No,
    Permit_Address.Permit_Fraction,
    Permit_Address.Permit_Direction,
    Permit_Address.Permit_Address,
    Permit_Address.Permit_Unit,
    Permit_Address.Permit_CityName,
    0,
    0,
    0
) as ADR

这将产生如下结果:

400 BELL STREET, SOMECITY

我想在WHERE条款中执行类似的操作:

WHERE ADR LIKE '%400 BELL STREET%'

这可能吗?

1 个答案:

答案 0 :(得分:2)

查询处理阶段的逻辑顺序是:

  1. FROM
  2. WHERE
  3. GROUP BY
  4. HAVING
  5. 选择
  6. ORDER BY
  7. 因此,您无法访问SELECT子句中WHERE中的别名

    使用此:

    WHERE
    dbo.pt_FormatAddress(
        Permit_Address.Permit_No,
        Permit_Address.Permit_Fraction,
        Permit_Address.Permit_Direction,
        Permit_Address.Permit_Address,
        Permit_Address.Permit_Unit,
        Permit_Address.Permit_CityName,
        0,
        0,
        0
    ) LIKE '%400 BELL STREET%'
    

    您还可以选择将主查询放在CTE中并使用其中的别名。

    这样的事情:

    ;WITH C AS(
        SELECT dbo.pt_FormatAddress(
            Permit_Address.Permit_No,
            Permit_Address.Permit_Fraction,
            Permit_Address.Permit_Direction,
            Permit_Address.Permit_Address,
            Permit_Address.Permit_Unit,
            Permit_Address.Permit_CityName,
            0,
            0,
            0
        ) as ADR
        FROM yourTable
    )
    SELECT *
    FROM C
    WHERE ADR LIKE '%400 BELL STREET%'
    

    LOGICAL QUERY PROCESSING