Sql 如何选择二进制列中的记录测试位?
我有两个表:其中一个包含列binary128,其中每一位都是某个标志。另外,我还有一个表包含需要在查询中检查的位位置列表 这是我如何进行一位查询的示例。 如何通用,即从第二个表的位置选择测试位的记录? 它应该是一个函数吗?什么Sql 如何选择二进制列中的记录测试位?,sql,sql-server,binary,bit,Sql,Sql Server,Binary,Bit,我有两个表:其中一个包含列binary128,其中每一位都是某个标志。另外,我还有一个表包含需要在查询中检查的位位置列表 这是我如何进行一位查询的示例。 如何通用,即从第二个表的位置选择测试位的记录? 它应该是一个函数吗?什么 DECLARE @nByteNum integer DECLARE @nBitNumInByte integer DECLARE @nMask integer DECLARE @nBigBitNum integer declare @t
DECLARE @nByteNum integer
DECLARE @nBitNumInByte integer
DECLARE @nMask integer
DECLARE @nBigBitNum integer
declare @t table(id int not null identity, id1 int, banner binary(128))
declare @bitpositions table(id int not null identity, position int)
insert into @bitpositions(position) values(8)
insert into @bitpositions(position) values(24)
insert into @bitpositions(position) values(30)
insert into @t(id1, banner)
select 1, 0x0
union all
select 1, 0x000100FF
union all
select 1, 0x010200FF
union all
select 10, 0x010208
union all
select 10, 0x000100
union all
select 10, 0x040000
select * from @t
-- This is for one bit
SET @nBigBitNum= 24
SET @nByteNum= @nBigBitNum/8
SET @nBitNumInByte= @nBigBitNum % 8 -- 0,1...6,7
SET @nMask = POWER(2, @nBitNumInByte ) -- 128,64,... 2,1
SET @nByteNum= @nByteNum +1
select * from @t where SUBSTRING(banner, @nByteNum,1)&@nMask=@nMask
SQL Server中的按位操作无法按预期的方式处理二进制数据。它们只能处理整数数据类型,如的MSDN页面上所述 检查查询中位掩码值的一般语法是:其中{Column}&{BitMaskedValue}={BitMaskedValue} 使用所需场景查看以下示例,尝试查找位位置为8和16的记录
-- 24 = 16 + 8
SELECT 24 & 16 -- 16
SELECT 24 & 8 -- 8
SELECT 24 & 17 -- 16
SELECT 24 & 32 -- 0
SELECT 24 & 26 -- 24
是的,但此查询工作正常:从@t中选择*其中SUBSTRINGbanner,@nByteNum,1&@nMask=@nMask;。另一个问题是如何优化大型表上的查询?有什么窍门吗-