2011-01-14 4 views
0

으로 변환합니다. this question (Sql Server convert integer to binary string과 비슷하지만 대신 varbinary (16)를 해당 텍스트 버전으로 변환하고 싶습니다.SQL Server 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)[email protected] 
select @value = convert(int, (@value/2)), @[email protected] 
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

@value % 2@value/2은 암시 적 변환을 수행하고 있습니다.

select @value = convert(int, (@value/2)) int로 명시 적 변환을 수행하므로 여기서 bigint로 변환 된 나누기가 2,147,483,647보다 큰 경우 varbinary (16)에 저장된 값에 대해 음의 int를 얻습니다. 음수 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 
+0

건배. 전체 범위를 얻으려면 CLR 함수를 만들어야합니다. – Nat

관련 문제