SQL Server - 使用查询查找按位OR值

时间:2011-10-06 15:44:04

标签: sql-server tsql

我有业务要求搜索数据库表,其中一列是按位整数,并从表中删除基值。

例如,假设我的表/结果集当前看起来像这样:

Value
-----
1
2
16
32
33

请注意,33存在,也是32 | 1.我需要做的是删除1和32值以返回:

Value
-----
2
16
33

显然我可以在SQL中使用循环结构 - 甚至在C#中的业务逻辑中 - 这样做但我想知道这是否可以使用查询?

2 个答案:

答案 0 :(得分:2)

这是一个应该有效的查询。

DELETE myTable WHERE myTable.Value in
(SELECT T1.Value
FROM myTable T1
CROSS JOIN myTable T2
WHERE T1.Value<>T2.Value AND T1.Value<T2.Value AND ((T1.Value | T2.VALUE)=T2.Value))

答案 1 :(得分:0)

尝试:

with cte(Value) as (
    select 1 as Value
    union all
    select 2
    union all
    select 16
    union all
    select 32
    union all
    select 33
)

--select values to be removed
select x1.Value
from cte x1
inner join cte x2 on x1.Value <> x2.Value 
inner join cte x3 on x1.Value <> x3.Value and x2.Value <> x3.Value
where x1.Value | x2.Value = x3.Value