使用别名"大约"在where子句中

时间:2015-11-02 01:09:14

标签: sql-server stored-procedures

我有一个错误:

  

无效的列名称Temp

我想在Temp子句中使用列where。我该怎么做?

ALTER PROCEDURE [dbo].[R_rpt1]
        @ltt int
    AS
    BEGIN
        SELECT ROW_NUMBER() OVER (ORDER BY YeuCauId) STT, a.name,
                CASE WHEN a.tt = 0 THEN 0
                    WHEN (a.tt = 1 AND a.code IN (Select code from SCHEMAB.dbo.databaseB)) THEN 3
                    WHEN  (a.tt = 1 ) THEN 1
                    WHEN a.tt=2 THEN 2
                    END as Temp
        FROM ViewPhieuYeuCau a
        WHERE Temp = @ltt
    END

1 个答案:

答案 0 :(得分:2)

使用子查询:

ALTER PROCEDURE [dbo].[R_rpt1]
    @ltt int
AS
BEGIN
    SELECT *
    FROM (
        SELECT ROW_NUMBER() OVER (ORDER BY YeuCauId) STT, a.name,
                CASE
                    WHEN a.tt = 0 THEN 0
                    WHEN a.tt = 1 AND a.code IN (Select code from SCHEMAB.dbo.databaseB) THEN 3
                    WHEN a.tt = 1 THEN 1
                    WHEN a.tt=2 THEN 2
                END as Temp
        FROM ViewPhieuYeuCau a
    ) t
    WHERE Temp = @ltt
END

由于WHERE子句首先在SELECT之前执行,Temp子句尚未识别WHERE。要解决此问题,您必须使用子查询。

Logical Processing Order of the SELECT statement