CASE语句bool错误

时间:2011-06-09 16:00:24

标签: sql case

如何将以下WHERE CASE语句更改为bool以使该语句有效?它给了我错误“在预期条件的上下文中指定的非布尔类型的表达式。”

WHERE (dma.DeviceId = @DeviceID AND dma.AssociationStart = @Start AND dma.AssociationEnd = @End) AND
CASE WHEN (dma.AssociationEnd IS NOT NULL)
    THEN (SELECT m.TimeStamp FROM Measurements m WHERE m.TimeStamp BETWEEN @Start AND @End)
 ELSE 
    (SELECT m.TimeStamp FROM Measurements m WHERE m.TimeStamp BETWEEN @Start AND (SELECT SYSDATETIMEOFFSET()))
END

2 个答案:

答案 0 :(得分:2)

也许你打算做以下事情:

SELECT m.Timestamp FROM Measurements m
WHERE dma.DeviceId = @DeviceID
  AND dma.AssociationStart = @Start
  AND dma.AssociationEnd = @End
  AND m.Timestamp BETWEEN @Start AND COALESCE(@End, SYSDATETIMEOFFSET())

但是dma.AssociationEnd = @End成功已经这一事实意味着dma.AssociationEnd@End都不为空。因此,COALESCE(以及原始问题中的整个CASE)是浪费时间。

(当然,这仅在具有SELECT的较大dma内才有意义。)

答案 1 :(得分:0)

也许:

WHERE dma.DeviceId = @DeviceID
  AND dma.AssociationStart = @Start
  AND dma.AssociationEnd = @End
  AND EXISTS
    CASE WHEN (dma.AssociationEnd IS NOT NULL)
      THEN ( SELECT m.TimeStamp
             FROM Measurements m
             WHERE m.TimeStamp BETWEEN @Start AND @End
           )
      ELSE ( SELECT m.TimeStamp
             FROM Measurements m
             WHERE m.TimeStamp BETWEEN @Start AND SYSDATETIMEOFFSET()
           )
    END