SQL 服务器比较运算符修饰符 ALL 不起作用?

SQL Server Comparison Operator Modifier ALL does not work?

似乎比较运算符修饰符 ALL 没有按预期工作。我正在使用 Microsoft SQL Server 2008 R2 Management Studio (v10.50.4000.0)。

declare @AllTest table 
(
    ID int identity,
    Crew int,
    Iteration int,
    Value varchar(200)
)

insert @AllTest
values
    (1, 1, 'a'),
    (2, 1, 'b'),
    (3, 1, NULL),
    (1, 2, 'd'),
    (1, 3, 'e'),
    (3, 2, NULL),
    (2, 2, 'a'),
    (2, 3, 'b'),
    (1, 4, NULL),
    (1, 5, 'f')

select
    *
from 
    @AllTest
where 
    1 = 1
    and Crew = 1
    and Value is not NULL   

select
    *
from
    @AllTest
where 
    1 = 1
    and Crew = 1
    and Value is not NULL
    and Iteration = all(select v from (values (1),(2),(3)) as t(v))

select
    *
from
    @AllTest
where
    1 = 1
    and Crew = 1
    and Value is not NULL
    and Iteration != all(select v from (values (1),(2),(3)) as t(v))

'Iteration = all' 的查询没有 return 任何结果,但它应该。 'Iteration != all' 确实按预期工作的查询。 (然而,这样的结果似乎更容易通过 'Iteration not in ' 实现,并且不需要使用类似 Table 值构造函数或联合的子查询来呈现值。)

无论如何,ALL 无法正常工作,并且 'Iteration = all(1,2,3)' 或 'Iteration != all(1,2,3)' 等简单表达式无效,这似乎真的很奇怪!

select
    *
from 
    @AllTest
where 
    1 = 1
    and Crew = 1
    and Value is not NULL
    and Iteration != all(1,2,3)

这是我的 SQL 服务器版本的问题还是我缺少什么?

如果 ALL 不起作用,那么构建查询的最佳替代方法是什么 return 应使用 ALL 生成的结果?

编辑: 我很抱歉没有让我的问题更清楚关于预期结果的问题。我正在寻找一种方法,当存在值为 NULL 且迭代等于 1、2 和 3 且没有缺失行的行时,只有结果 returned。

我希望这是有道理的。

另外,我看到 'Iteration = all' 是如何寻找单行的,我试过 'Iteration in all' 这在语义上更有意义,但它被认为是不正确的语法。

Iteration = all(select v from (values (1),(2),(3)) as t(v))

表示

Iteration = 1 AND Iteration = 2 AND Iteration = 3

WHERE 一次对一行进行操作。上述任何一行都不可能成立 - 因此没有结果。


根据您的编辑,获得所需行为的一种方法是

;WITH CTE
     AS (SELECT *
         FROM   @AllTest
         WHERE  Crew = 1
                AND Value IS NOT NULL)
SELECT *
FROM   CTE
WHERE  NOT EXISTS (SELECT v
                   FROM   (VALUES (1),
                                  (2),
                                  (3)) AS t(v)
                   EXCEPT
                   SELECT c2.Iteration
                   FROM   cte c2) 

我认为您想使用 Any 而不是 ALL。所有适用于 > 和 <,例如:

select
    *
from @AllTest
where 1 = 1
    and Crew = 1
    and Value is not NULL
    and Iteration > all(select v from (values (1),(2),(3)) as t(v))

Returns带f的记录

ID  Crew    Iteration   Value
10  1          5          f

这是任何一个:

select
    *
from @AllTest
where 1 = 1
    and Crew = 1
    and Value is not NULL
    and Iteration = Any(select v from (values (1),(2),(3)) as t(v))

ID  Crew    Iteration   Value
1   1   1   a
4   1   2   d
5   1   3   e