SQL 服务器中的按位运算
Bitwise operation in SQL Server
我有一个 CategoryId 列,它会同时存储多个值,其中一些有 1 (BA)、2 (SA) 或 3(两者)。我不确定这是不是正确的方法。
例如,查询会带来所有记录,因为 3 包括 1 和 2。如果我想要具有 both 类别的行,则按位将不起作用。我认为我混淆了术语。
示例数据和查询:
CREATE TABLE #Payment (Id INT, Name NVARCHAR(50), CategoryId INT)
INSERT #Payment (Id, Name, CategoryId) VALUES(1, N'A', 1) --BA
INSERT #Payment (Id, Name, CategoryId) VALUES(1, N'B', 2) --SA
INSERT #Payment (Id, Name, CategoryId) VALUES(1, N'C', 3) --BA and SA
INSERT #Payment (Id, Name, CategoryId) VALUES(1, N'D', 2) --SA
DECLARE @Value INT = 3
SELECT *
FROM #Payment
WHERE (CategoryId & @Value) = CategoryId
WHERE 子句中需要进行细微的更正。应该是:
WHERE (CategoryID & 3) = 3 -- bits 1 and 2 are set (matches 3, 7, 11, 15, ...)
为了完整起见,这里还有其他变体:
WHERE (CategoryID & 3) <> 0 -- bits 1 or 2 are set (matches 1, 2, 3, 5, 6, 7, 9, 10, 11, ...)
WHERE (CategoryID & 3) = 0 -- bits 1 and 2 are not set (matches 0, 4, 8, 12, ...)
WHERE (CategoryID & 3) = CategoryID -- bits other than 1 and 2 are not set (matches 0, 1, 2, 3)
我有一个 CategoryId 列,它会同时存储多个值,其中一些有 1 (BA)、2 (SA) 或 3(两者)。我不确定这是不是正确的方法。
例如,查询会带来所有记录,因为 3 包括 1 和 2。如果我想要具有 both 类别的行,则按位将不起作用。我认为我混淆了术语。
示例数据和查询:
CREATE TABLE #Payment (Id INT, Name NVARCHAR(50), CategoryId INT)
INSERT #Payment (Id, Name, CategoryId) VALUES(1, N'A', 1) --BA
INSERT #Payment (Id, Name, CategoryId) VALUES(1, N'B', 2) --SA
INSERT #Payment (Id, Name, CategoryId) VALUES(1, N'C', 3) --BA and SA
INSERT #Payment (Id, Name, CategoryId) VALUES(1, N'D', 2) --SA
DECLARE @Value INT = 3
SELECT *
FROM #Payment
WHERE (CategoryId & @Value) = CategoryId
WHERE 子句中需要进行细微的更正。应该是:
WHERE (CategoryID & 3) = 3 -- bits 1 and 2 are set (matches 3, 7, 11, 15, ...)
为了完整起见,这里还有其他变体:
WHERE (CategoryID & 3) <> 0 -- bits 1 or 2 are set (matches 1, 2, 3, 5, 6, 7, 9, 10, 11, ...)
WHERE (CategoryID & 3) = 0 -- bits 1 and 2 are not set (matches 0, 4, 8, 12, ...)
WHERE (CategoryID & 3) = CategoryID -- bits other than 1 and 2 are not set (matches 0, 1, 2, 3)