如何将以下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
答案 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