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

时间:2018-06-28 14:34:35

标签: sql sql-server sql-server-2008 tsql 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

如果看到,则“重新选择的二进制值”与原始值不匹配。 您能检查我哪里出问题了吗?

1 个答案:

答案 0 :(得分:1)

要将10字节的二进制文件“转换”为 non-binary ,您需要一种数据类型,该数据类型至少具有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字节的二进制文件拆分为多个块,并将其作为单独的数字:

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;