sql - 如何在sql server中在两个二进制类型之间进行按位异或?

标签 sql sql-server tsql

根据此链接: Bitwise Operators (Transact-SQL) 我们可以在二进制和 int、smallint、tinyint 之间进行按位运算,反之亦然。

但是如何在 sql server 中在两个二进制类型之间进行按位异或运算呢? 或者,如果这是不可能的,我如何将二进制/varbinary 拆分为单个字节?

我要求这个的原因是因为我需要对两个大于 max int 值的数字进行异或。 谢谢。

最佳答案

代码块中的所有注释

-- variables
declare @vb1 binary(16), @vb2 binary(16), @lo binary(8), @hi binary(8)

-- 2 guids to compare
declare @guid1 uniqueidentifier set @guid1 = '96B4316D-1EA7-4CA3-8D50-FEE8047C1329'
declare @guid2 uniqueidentifier set @guid2 = 'FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF'

-- split every 8 bytes into a binary(8), which is a bigint, the largest size usable with XOR
select @vb1 = @guid1, @vb2 = @guid2

-- xor the high and low parts separately
select @hi = convert(binary(8), substring(@vb1,1,8)) ^ convert(bigint, substring(@vb2,1,8))
select @lo = convert(binary(8), substring(@vb1,9,8)) ^ convert(bigint, substring(@vb2,9,8))

-- the final result, concatenating the bytes using char(8) - binary -> uniqueidentifier
select 'A', @guid1 union all
select 'B', @guid2 union all
select 'A XOR B = ', convert(uniqueidentifier, convert(binary(16),convert(char(8),@hi) + convert(char(8),@lo)))

关于sql - 如何在sql server中在两个二进制类型之间进行按位异或?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4833807/

相关文章:

sql - 活跃用户 SQL 查询

sql - 获取缺少答案的调查问卷列表

sql - 从 SQL Server Service Broker 提取消息

sql - 选择 row_number 或假身份

sql - 从 XML 列中获取所有值

php - 用 PHP 编写的简单/快速的文件上传脚本是什么?

mysql - 使用另一个表更新一个表

mysql - 选择行匹配计算

SQL Server,使用表作为队列

sql - 避免子查询根据基本记录的日期从同一个表中选择记录