Boolean operations on bit columns

时间:2018-03-09 19:16:35

标签: sql sql-server

How can I perform boolean operations on columns of datatype bit? For example, how can I perform the logical "AND" of an entire column?

If the bits were cast as ints, then taking the min of the column would work as "AND" and checking if the sum is greater than zero would work for "OR", but is there any way to do it directly without the cast?

I would like to do something like

SELECT AND(bitColumn)
FROM tempTable

3 个答案:

答案 0 :(得分:0)

您可以转换为数字。对于http_proxy=http://proxy:1234 https_proxy=http://proxy:1234

AND

对于SELECT CAST((CASE WHEN MIN(CAST(bitColumn as int)) = 1 THEN 1 ELSE 0 END) as BIT) FROM tempTable; ,请使用OR

答案 1 :(得分:0)

没有明确的函数允许您对存储在表列中的所有值执行AND或OR运算。最简单的方法是简单地将值转换为INT,并将SUM或MAX值与case语句结合使用。

您可以使用按位运算符执行相同的操作,而无需执行任何类型转换,但这并不简单。我在下面列举了一个例子,主要是为了好玩:)

-- ----------------------------------------------------
-- OR - Example
-- ----------------------------------------------------
DECLARE @LogicalOrResult BIT = 0; -- Initialize result as false.

-- Create sample data
SELECT * INTO #TableLogic
FROM    (
            SELECT 1 as ID, CAST(0 AS BIT) AS BitColumn UNION ALL
            SELECT 2 as ID, CAST(0 AS BIT) AS BitColumn UNION ALL
            SELECT 3 as ID, CAST(0 AS BIT) AS BitColumn UNION ALL
            SELECT 4 as ID, CAST(0 AS BIT) AS BitColumn UNION ALL
            SELECT 5 as ID, CAST(1 AS BIT) AS BitColumn
        ) Logic

-- OR all column values.
SELECT  @LogicalOrResult |= BitColumn
FROM    #TableLogic

-- Expected result: 1
SELECT @LogicalOrResult AS Result

DROP TABLE #TableLogic;

GO
-- ----------------------------------------------------
-- AND - Example
-- ----------------------------------------------------
DECLARE @LogicalOrResult BIT = 1; -- Initialize result as true.

-- Create sample data
SELECT * INTO #TableLogic
FROM    (
            SELECT 1 as ID, CAST(0 AS BIT) AS BitColumn UNION ALL
            SELECT 2 as ID, CAST(1 AS BIT) AS BitColumn UNION ALL
            SELECT 3 as ID, CAST(1 AS BIT) AS BitColumn UNION ALL
            SELECT 4 as ID, CAST(1 AS BIT) AS BitColumn UNION ALL
            SELECT 5 as ID, CAST(1 AS BIT) AS BitColumn
        ) Logic

-- AND all column values.
SELECT  @LogicalOrResult &= BitColumn
FROM    #TableLogic

-- Expected result: 0
SELECT @LogicalOrResult AS Result

DROP TABLE #TableLogic;

答案 2 :(得分:0)

没有强制转换,没有MIN:

SELECT IIF(1=ALL(SELECT bitColumn FROM tempTable),1,0)