SQL case when expression between?

SQL case when expression between?

有没有办法做类似的事情:

DECLARE @x INT;
DECLARE @y INT;
SET @x=45;
SET @y=30;

SELECT 
    CASE @x - @y 
       WHEN BETWEEN 2 AND 3 
          THEN 'true' 
          ELSE 'false' 
    END

我收到一个错误:

Msg 156, Level 15, State 1
Incorrect syntax near the keyword 'BETWEEN'

SELECT CASE WHEN @x - @y BETWEEN 2 AND 3 
            THEN 'true' 
            ELSE 'false' 
       END

CASE expr WHEN val THEN ... 仅适用于相等性检查,不适用于 BETWEEN 等更复杂的条件。在你的情况下,你需要使用像 CASE WHEN val BETWEEN ... THEN ...:

这样的结构
SELECT CASE WHEN @x - @y BETWEEN 2 AND 3 THEN 'true' ELSE 'false' END

或者,您可以使用:

SELECT CASE @x - @y
    WHEN 2 THEN 'true'
    WHEN 3 THEN 'true'
    ELSE 'false'
END