查询以比较select语句中的强制转换

时间:2015-10-19 17:45:10

标签: sql sql-server tsql date casting

我有一个查询,我在拉三个字段,并将它们转换为日期。我希望然后在同一个select语句中运行一个比较,但是我在试图比较的字段上得到一个无效的列名。但是,订单工作正常。 / scratching_head

SQL Server 2012

SELECT 
UTCSID,
UTLCID,

/* put utonmm, utondd, utonyy together as a date called uton */
CAST(
  CAST(UTONMM as varchar) + '/' + 
  CAST(UTONDD as varchar) + '/' +
  CASE WHEN UTONCV = '1' 
    THEN RIGHT('20' + CONVERT(varchar(4), RIGHT('00' + CONVERT(varchar(4), UTONYY),2)),4)
  ELSE RIGHT('19' + CONVERT(varchar(4), UTONYY),4)
  END 
AS DATETIME) AS UTON, 

/* put utofmm, utofdd, utofyy together as a date called utoff */
CAST(
CASE WHEN UTOFMM > '0' 
THEN
    CAST(UTOFMM as varchar) + '/' + 
    CAST(UTOFDD as varchar) + '/' +
    CASE WHEN UTOFCV = '1' 
        THEN RIGHT('20' + CONVERT(varchar(4), RIGHT('00' + CONVERT(varchar(4), UTOFYY),2)),4)
        ELSE RIGHT('19' + CONVERT(varchar(4), UTOFYY),4)
    END
END
AS DATETIME) AS UTOFF,

UTCBAL,
UTDBAL,
UTUNPS

FROM [HTEDTA].[THOR].[HTEDTA].UT210AP
WHERE UTLCID = '885570' AND UTOFF > GETDATE() ORDER BY UTON DESC

此声明返回:

Invalid column name: 'UTOFF'

1 个答案:

答案 0 :(得分:0)

问题是在解析utoff子句时别名where是不可知的。

解决它的一种方法是将查询包装在公用表表达式中,并将where子句应用于:

WITH CTE AS (
    SELECT UTCSID, UTLCID,    
    /* put utonmm, utondd, utonyy together as a date called uton */
    CAST(
     CAST(UTONMM as varchar) + '/' + 
     CAST(UTONDD as varchar) + '/' +
     CASE WHEN UTONCV = '1' 
       THEN RIGHT('20' + CONVERT(varchar(4), RIGHT('00' + CONVERT(varchar(4), UTONYY),2)),4)
     ELSE RIGHT('19' + CONVERT(varchar(4), UTONYY),4)
     END 
    AS DATETIME) AS UTON, 

    /* put utofmm, utofdd, utofyy together as a date called utoff */
    CAST(
    CASE WHEN UTOFMM > '0' 
    THEN
       CAST(UTOFMM as varchar) + '/' + 
       CAST(UTOFDD as varchar) + '/' +
       CASE WHEN UTOFCV = '1' 
          THEN RIGHT('20' + CONVERT(varchar(4), RIGHT('00' + CONVERT(varchar(4), UTOFYY),2)),4)
          ELSE RIGHT('19' + CONVERT(varchar(4), UTOFYY),4)
       END
    END
    AS DATETIME) AS UTOFF,

    UTCBAL, UTDBAL, UTUNPS    
    FROM [HTEDTA].[THOR].[HTEDTA].UT210AP
)
SELECT * 
FROM CTE
WHERE UTLCID = '885570' AND UTOFF > GETDATE()