CASE WHEN语法SQL Server 2008

时间:2014-09-04 02:08:49

标签: sql sql-server sql-server-2008

我在SQL Server中遇到CASE WHEN语法问题。我从以下语法中做错了吗?我在SQL Server视图上使用此语法。请检查以下语法:

SELECT 
    t1.ID ,
    t1.ClassID ,
    t1.theDate ,
    t1.theTime ,
    t1.Number01 ,
    MAX(t2.Number01) AS Prev_Number01 ,
    CASE
        WHEN ( ( t1.Number01 -   MAX( t2.Number01 ) ) < 0
          THEN ( 100000      - ( MAX( t2.Number01 ) ) + t1.Number01 ) ,
               ( t1.Number01 -   MAX( t2.Number01 ) ) )
    END AS _Number01 ,
    t1.Number02 , 
    MAX( t2.Number02 ) AS Prev_Number02 ,
    CASE
        WHEN ( ( t1.Number02 -   MAX( t2.Number02 ) ) < 0
          THEN ( 100000      - ( MAX( t2.Number02 ) ) + t1.Number02 ) ,
               ( t1.Number02 -   MAX( t2.Number02 ) ) )
    END AS _Number02 ,
    CONVERT(Decimal(18,3) ,
        (   t1.Number01
          - MAX(t2.Number01)
        ) /
        POWER(
          POWER(
            COALESCE( t1.Number01 - MAX(t2.Number01) , 0 ) ,
            2 )
          + POWER(
              COALESCE( t1.Number02 - MAX(t2.Number02), 0) ,
              2 ) ,
          0.5
          )
        ) AS _NumberA ,
    t1.Number03 ,
    t1.Number04 ,
    t1.Number05 ,
    t1.AD ,
    t1.GM ,
    MAX(t2.GM) AS Prev_GM ,
    t1.GM - MAX(t2.GM) AS AX ,
    t1.DC ,
    t1.MW ,
    t1.ULH ,
    t1.UL ,
    CONVERT(Decimal(18,3), 
        t1.MW / POWER( POWER(t1.MW,2) + POWER(t1.UL,2) , 0.5 )
        ) AS UT ,
    t1.RE ,
    t1.FV ,
    t1.TG ,
    t1.NM ,
    t1.CK
FROM            
    dbo._CTProduction AS t1
LEFT OUTER JOIN 
    dbo._CTProduction AS t2 ON t2.ClassID  = t1.ClassID
                            AND t2.Number01 < t1.Number01
                            AND t2.Number02 < t1.Number02
                            AND t2.GM < t1.GM
GROUP BY 
    t1.ID, t1.ClassID, t1.theDate, t1.theTime,
    t1.Number01, t1.Number02, t1.Number03, t1.Number04, t1.Number05,
    t1.AD, t1.GM, t1.DC, t1.MW, t1.ULH, t1.UL,
    t1.RE, t1.FV, t1.TG, t1.NM, t1.CK

这是错误消息:

  

Msg 156,Level 15,State 1,Line 4
  关键字&#39; THEN&#39;附近的语法不正确。

第6行还有一个CASE语句。与第4行相同。任何人都可以帮忙解决这个问题吗?

3 个答案:

答案 0 :(得分:2)

这是case声明:

CASE WHEN ((t1.Number01 - MAX(t2.Number01)) < 0
     THEN (100000 - (MAX(t2.Number01)) + t1.Number01),
(t1.Number01 - MAX(t2.Number01))) END AS _Number01, t1.Number02, 
MAX(t2.Number02) AS Prev_Number02, 

这不正确。我不确定你想要什么,但这在语法上是正确的:

(CASE WHEN t1.Number01 - MAX(t2.Number01) < 0
      THEN 100000 - MAX(t2.Number01) + t1.Number01
      ELSE t1.Number01 - MAX(t2.Number01)
 END) AS _Number01, t1.Number02, 
MAX(t2.Number02) AS Prev_Number02, 

换句话说,逗号不是语法的一部分,而您缺少else(如果这是您的意图)。

答案 1 :(得分:0)

您错过了ELSE短语。相反,您可以使用逗号后跟备用值。

CASE WHEN (t1.Number01 - MAX(t2.Number01)) < 0
    THEN (100000 - MAX(t2.Number01) + t1.Number01)
    ELSE (t1.Number01 - MAX(t2.Number01))
END

可以找到CASE声明文档here

答案 2 :(得分:0)

如果您重新编写代码以使其接近可读(参见上面的编辑),您可能会注意到whenthen条款中的括号不平衡。更不用说then子句尝试返回一个以通信分隔的值集。