为什么我的case语句会抛出错误,'='附近的语法不正确?

时间:2014-11-10 19:58:52

标签: sql sql-server tsql

为什么我的case语句会抛出此错误:

Msg 102,Level 15,State 1,Line 2 '='附近的语法不正确。

代码:

Create PROCEDURE [dbo].[Chart_SelectSmsComplaintsValidity]

 @FromDate datetime,
 @ToDate datetime

AS
BEGIN

    Select COUNT(ReceivedMessages.ID) As ReceivedMessageID, 
    CASE ReceivedMessages.IsComplaint WHEN ReceivedMessages.IsComplaint=0 
    THEN 'Incomplete'
    WHEN ReceivedMessages.IsComplaint=1 THEN 'Complete'
    WHEN ReceivedMessages.IsComplaint=-3 THEN 'Inappropriate' END from ReceivedMessages 

    where ReceivedMessages.ReceivedDateTime >= @FromDate AND ReceivedMessages.ReceivedDateTime <= @ToDate
    Group By ReceivedMessages.IsComplaint




END

2 个答案:

答案 0 :(得分:3)

您正在组合两种不同形式的CASE声明。您可以通过这种方式简化它,因为您在每种情况下都要比较相同的表达式:

CASE ReceivedMessages.IsComplaint
  WHEN 0  THEN 'Incomplete'
  WHEN 1  THEN 'Complete'
  WHEN -3 THEN 'Inappropriate' 
END from ReceivedMessages 

替代方案是:

CASE
  WHEN ReceivedMessages.IsComplaint=0  THEN 'Incomplete'
  WHEN ReceivedMessages.IsComplaint=1  THEN 'Complete'
  WHEN ReceivedMessages.IsComplaint=-3 THEN 'Inappropriate' 
END

答案 1 :(得分:1)

错误在此行

CASE ReceivedMessages.IsComplaint WHEN ReceivedMessages.IsComplaint=0 

应该是这样的

CASE WHEN ReceivedMessages.IsComplaint=0 THEN 'Incomplete'
WHEN ReceivedMessages.IsComplaint=1 THEN 'Complete'
WHEN ReceivedMessages.IsComplaint=-3 THEN 'Inappropriate' END