【问题标题】:SQL Server convert varbinary(16) to binary textSQL Server 将 varbinary(16) 转换为二进制文本
【发布时间】:2011-01-14 01:23:45
【问题描述】:

类似于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

也许我在函数中进行了一些隐式转换,因为该函数仅适用于正整数。

【问题讨论】:

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


    【解决方案1】:

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

    select @value = convert(int, (@value / 2)) 正在对 int 进行显式转换,因此在这里您将获得 varbinary(16) 中存储的值的负 int,在转换为 bigint 的除法之后大于 2,147,483,647。 负整数的 % 会给你一个 -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
    

    【讨论】:

    • 干杯。为了获得完整的范围,我应该创建一个 CLR 函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    相关资源
    最近更新 更多