SQL Server 从二进制数据类型到数字数据的转换问题

标签 sql sql-server sql-server-2008 t-sql cdc

我正在尝试保留 Sql 服务器 CDC 表之一中的值,该表的列数据类型为“Binary(10)”。我想将其转换为“数字”格式,然后将其转换回“二进制(10)”。

例如

declare @binary_data binary(10),@binary2 as binary(10)

select  @binary_data = 0x000000180003727C0006

Select Convert(int,0x00000018) as [PrecesionValue]
Select Convert(int,0x000) as [ScaleValue]

declare @Numeric as numeric(24,0) --Setting Numeric(PrecesionValue, ScaleValue)

Select @Numeric =Convert(numeric(24,0),@binary_data) 

Select @binary2 = Convert(binary(10),@Numeric) 

print @binary_data
print @Numeric
print @binary2

输出:

0x000000180003727C0006  //Initial binary data

393340                  //Converted Numeric value

0x0000180000017C000600  //Re-converted back to Binary value

如果您看到,重新转换的二进制值与原始值不匹配。 你能检查一下我哪里出错了吗?

最佳答案

要将 10 字节二进制文件“转换”为非二进制文件,您需要一个至少有 10 字节存储空间的数据类型。但是您不应该依赖 SQL Server 使用的位模式来存储复杂的数据类型。

我想建议两种方法:

--this is your binary
declare @binary1 binary(10) 
set @binary1 = 0x000000180003727C0006;
select  @binary1; 

--XML will translate binaries to base64 implicitly
declare @string varchar(100);
set @string = (SELECT @binary1 AS [*] FOR XML PATH(''),TYPE).value('.','varchar(100)');
select @string,LEN(@string);

--this is the approach to translate the base64 back to a binary
declare @binary2 binary(10);
set @binary2=CAST('<x>' + @string + '</x>' AS XML).value('.','varbinary(10)');
select @binary2; 

--the second approach is a GUID (16 byte)
declare @guid uniqueidentifier;
set @guid=@binary1
select @guid;

--a GUID is a simple chain of bytes, easy to cast
set @binary2=CAST(@guid AS VARBINARY(10));
select @binary2; 

更新:我想到了另一个想法

讨论二进制和字符串类型是有原因的 in one topic 。您可以将 10 字节二进制文件分割成 block ,并将它们作为分隔的数字:

declare @binary1 binary(10) 
set @binary1 = 0x00000180003727C0006;
select  @binary1,SUBSTRING(@binary1,1,4) AS Byte0to3 
                ,SUBSTRING(@binary1,5,4) AS Byte4to8
                ,SUBSTRING(@binary1,10,2) AS Byte9to10;

declare @int1 INT, @int2 INT, @smallint smallint;
select  @int1 =     SUBSTRING(@binary1,1,4)  
       ,@int2 =     SUBSTRING(@binary1,5,4) 
       ,@smallint = SUBSTRING(@binary1,10,2);
select @int1,@int2,@smallint;

declare @binary2 binary(10);
set @binary2 = CAST(@int1 AS binary(4)) + CAST(@int2 AS binary(4)) + CAST(@smallint AS binary(2));
select @binary2;

关于SQL Server 从二进制数据类型到数字数据的转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51085563/

相关文章:

sql - 对于同一行上的每个显示 SQL Server

mysql - 根据其他 2 个表中的列值更新表

php - over() 子句出错 am 根据 id 计算 mysql 中下一个或上一个值的行

sql - SQL或Access中的排序表

sql - 在 Rails 中分组和计数

sql-server - 如何在 SQL Server 2008 中存储图像 blob 数据?

c# - 构建电子邮件发件人服务

sql-server-2008 - 在存储过程中计算加权(贝叶斯)平均分数/索引?

python - 来自 SQL Server 的 "Invalid precision or scale value"错误,使用 pypyodbc for Decimal( '0.00' )、Decimal( '0.12' )

sql - 优化 Hibernate Sequence ID 生成