Storing multiple checkBox values in database field

时间:2015-09-01 22:56:41

标签: sql binary

I have a database that is storing the value of multiple check boxes in a single field represented by a single number. Each check box is assigned a value that is a power of 2. For example, the first check box is assigned 1, then 2, then 4, then 8, 16 and 32. So, if the first, second and third check boxes were checked the value would be 7. No other combination can create a 7 so we know that the first 3 check boxes are checked.

My issue is that I can figure this out on paper to tell which boxes are checked but I can't figure out the math on how to do it in SQL. I need take a number such as 63 and figure out what check boxes are checked in the front end based on their power of 2 values. Hope this makes sense. Thanks

2 个答案:

答案 0 :(得分:2)

要检查这些位是否已设置,您需要使用& operator (Bitwise AND),如下所示:

DECLARE @Value      INT = 63
;WITH   Sequence    AS
(
    SELECT      0 as Number UNION ALL
    SELECT      Number + 1
    FROM        Sequence
    WHERE       Number < 30
)
SELECT          Number,
                POWER(2, Number) [Power], 
                CASE    WHEN @Value & POWER(2, Number) = 0
                        THEN 0
                        ELSE 1
                END     [IsBitSet?] 
FROM            Sequence

或者,对于另一个可视化:

DECLARE @Value      INT = 63
;WITH   Sequence    AS
(
    SELECT  0 as Number UNION ALL
    SELECT  Number + 1
    FROM    Sequence
    WHERE   Number < 30
)
SELECT      *
FROM
(
    SELECT  Number,
            CASE    WHEN @Value & POWER(2, Number) = 0
                    THEN 0
                    ELSE 1
            END     [IsBitSet?] 
    FROM    Sequence
)   AS      [Source]
PIVOT
(
    MAX     ([IsBitSet?])
    FOR     Number IN
    (
            [00], [01], [02], [03], [04], [05], [06], [07],
            [08], [09], [10], [11], [12], [13], [14], [15],
            [16], [17], [18], [19], [20], [21], [22], [23],
            [24], [25], [26], [27], [28], [29], [30]
    )
)   AS      [Pivot]

答案 1 :(得分:0)

You need do use binary operator, but probably in your UI front end not in SQL.

Even when in sql you can also do binary operation.

for example in C# you define constants

enum checkbox {
     check_1 = 1,
     check_2 = 2,
     check_3 = 4,
     check_4 = 8,
     check_5 = 16,
     check_6 = 32,
     check_7 = 64,
     check_8 = 128
}

So if you value in sql is 63 you do

if (value & checkbox.check_1 == 1) {
    checkbox1.checked = true;
}
if (value & checkbox.check_2 == 1) {
    checkbox2.checked = true;
}
...
...
if (value & checkbox.check_8 == 1 ) {
    checkbox8.checked = true;
}