SQL Server将varbinary(16)转换为二进制文本

时间:2011-01-14 01:23:45

标签: sql-server type-conversion implicit-conversion

this question (Sql Server convert integer to binary string类似,但我想将varbinary(16)转换为其文本版本。

我正在做一些悲惨的错误,因为我的代码的结果会证明。

create function GetGuidBinaryString (@value varbinary(16))
returns varchar(128)
as
begin
declare @vsresult varchar(128) 
declare @inti int 
select @inti = 128, @vsresult = '' 
while @inti>0 
begin 
select @vsresult=convert(char(1), @value % 2)+@vsresult 
select @value = convert(int, (@value / 2)), @inti=@inti-1 
end 

return @vsresult
end


create table #values (binvalue varchar(128))

delete from #values

declare @intcount int
select @intcount = 0
while @intcount < 100
begin
    insert into #values select dbo.GetGuidBinaryString(convert(varbinary(16),convert(bigint,2147483640) + @intcount))
    select @intcount = @intcount+1
end


select * from #values

也许在函数中有一些隐式转换,因为函数只对正整数有效。

1 个答案:

答案 0 :(得分:1)

@value % 2@value / 2正在进行隐式转换。

select @value = convert(int, (@value / 2))正在显式转换为int,所以在这里你得到一个负int,用于存储在varbinary(16)中的值,在转换为bigint的除法之后大于2,147,483,647。 负int的%会给你一个-1。

我认为不可能使用%和/将varbinary(16)转换为二进制。它们只适用于int / bigint等。

这是一个适用于正bigint值的转换例程。我不知道你对负bigint值的期望是什么。 在函数调用中将varbinary(16)字段转换为bigint,也许它可以满足你的需要。 我确信它不适用于您可以存储在varbinary(16)字段中的所有可能值。

create function BigIntToBin (@v bigint)
returns varchar(256)
as
begin
    declare @res varchar(256)
    declare @i int

    set @i = 128
    set @res = ''

    while @i > 0
    begin
        if @v % 2 = 0
            set @res = '0' + @res
        else    
            set @res = '1' + @res
        set @v = @v / 2
        set @i = @i - 1
    end
    return @res
end