小编典典

SQL之间的from和to值的顺序

sql

我在SQL Server中创建一个简单的过程,如下所示。

DECLARE @num int;
SET @num = 5;
SELECT @num WHERE @num BETWEEN 1 AND 10;
SELECT @num WHERE @num BETWEEN 10 AND 1;

如果运行此命令,则第一个选择语句将给您5,第二个选择语句将不返回任何内容。对于这是为什么我感到困惑,因为两种情况都应该返回true,因为5在10和1之间以及在1和10之间。

BETWEEN 10 AND 1线路违反逻辑是有原因的吗?

谢谢


阅读 360

收藏
2021-04-14

共1个答案

小编典典

这就是SQL的标准(已确定为标准)。

x BETWEEN a AND b

代表

( a <= x )  AND  ( x <= b )

请参阅第211页,其中包括:
SQL-92规范(审查草案的副本)

   8.3  <between predicate>

     Function
     Specify a range comparison.

     Format
     <between predicate> ::=
          <row value constructor> [ NOT ] BETWEEN
            <row value constructor> AND <row value constructor>

     Syntax Rules
     1) The three <row value constructor>s shall be of the same degree.
     2) Let respective values be values with the same ordinal position
        in the two <row value constructor>s.
     3) The data types of the respective values of the three <row value
        constructor>s shall be comparable.
     4) Let X, Y, and Z be the first, second, and third <row value con-
        structor>s, respectively.
     5) "X NOT BETWEEN Y AND Z" is equivalent to "NOT ( X BETWEEN Y AND
        Z )".
     6) "X BETWEEN Y AND Z" is equivalent to "X>=Y AND X<=Z".

我知道,唯一不符合标准(并遵循您的逻辑)的RDBMS是MS-Access。

2021-04-14