如何查看子值是否在屏蔽值中

How to see if a sub value is in masked value

我遇到了一些将多个复选框值存储到数据库中的 1 个值的代码。

这通过为每个值分配一个基数 2^n 值,并将所有选定值相加并存储该结果来实现。

我想知道如何在数据库中查询在数据库中存储的值中具有特定值的记录。

例子

Checkbox 1 = 2
Checkbox 2 = 4
Checkbox 3 = 8
Checkbox 4 = 16

假设选中了复选框 1 和 3。我们将在数据库中存储 10 个。

我将如何查询在存储在数据库 (10) 中的结果值中选中了复选框 1(值 2)的记录?

这是 sql 服务器。

您可以按位使用 AND:

SELECT *
FROM tab
WHERE answer & 10 = 10

@@OPTIONS 上使用的类似方法:

The @@OPTIONS function returns a bitmap of the options, converted to a base 10 (decimal) integer.

To decode the @@OPTIONS value, convert the integer returned by @@OPTIONS to binary, and then look up the values on the table at Configure the user options Server Configuration Option. For example, if SELECT @@OPTIONS; returns the value 5496, use the Windows programmer calculator (calc.exe) to convert decimal 5496 to binary. The result is 1010101111000. The right most characters (binary 1, 2, and 4) are 0, indicating that the first three items in the table are off.

正在检查ANSI_NULLS

To view the current setting for this setting, run the following query:

DECLARE @ANSI_NULLS VARCHAR(3) = 'OFF';  
IF ( (32 & @@OPTIONS) = 32 ) SET @ANSI_NULLS = 'ON';  
SELECT @ANSI_NULLS AS ANSI_NULLS; 

你可以使用按位运算&

以12为例。 12 的按位等效为 1100。如果您想知道复选框 3 是否被选中,您需要与 8 进行比较(等效 1000

1100
1000
-----
1000 => 8

所以你的最终查询是

SELECT * from Table1 WHERE answer & 8 = 8