位操作函数

适用于:SQL Server 2022 (16.x) Azure SQL 数据库Azure SQL 托管实例Microsoft Fabric 中的 SQL 分析终结点Microsoft Fabric 中的仓库

位操作函数,例如移动、检索(获取)、设置或计算整数或二进制值中的单个位,让你能够比使用单个位更有效地处理和存储数据。

位有两个值(10,代表 onoff,或者 truefalse)。 字节由 8 位序列组成。 SQL Server 中的位操作函数将字节中的“最左边”位视为最大(最重要的)位。 在位操作函数中,位从右到左进行编号,位 0 是最右边的位,最小位 7 是最左边和最大的位。

例如,二进制序列 00000111 是数字 7 的十进制等效项。 可以使用 2 的幂计算出来,如下所示:

00000111 = (2^2 + 2^1 + 2^0 = 4 + 2 + 1 = 7)

这实际上意味着,虽然 SQL Server 将此值存储为 11100000(字节反转),但位操作函数会将其视为 00000111

查看多个字节时,第一个字节(从左到右读取)是最大的。

可以使用下图来直观呈现 SQL Server 的位操作函数如何解释位和字节表达式值以及位偏移。

int

Diagram showing an int value where 4 bytes represent the reversed binary of each byte from left to right.

smallint

Diagram showing a small int value where the first byte represents bits 15 to 8, and the second byte represents bits 7 to 0.

函数

有五种函数可用于在 SQL Server 中操作位:

这五个函数都旨在对 tinyint、smallint、int、bigint、binary(n) 和 varbinary(n) 数据类型进行操作。

不支持以下类型:varchar、nvarchar、image、ntext、text、xml 和 table。

备注

在初始实现中,链接服务器中的位操作函数的分布式查询功能或即席查询 (OPENQUERY) 不受支持。