SQL varbinary varchar 互转

--==============================================
    --  FUNCTION  varbin2hexstr
    --  将 varbinary 类型的数据转换为 varchar 类型
    --==============================================
    
    IF OBJECT_ID ('dbo.varbin2hexstr') IS NOT NULL
        DROP FUNCTION dbo.varbin2hexstr
    GO
    
    CREATE function varbin2hexstr(
    @bin varbinary(8000)
    )returns varchar(8000)
    as
    begin
        declare @re varchar(8000),@i int
        select @re='',@i=datalength(@bin)
        while @i>0
            select @re=substring('0123456789ABCDEF',substring(@bin,@i,1)/16+1,1)
                    +substring('0123456789ABCDEF',substring(@bin,@i,1)%16+1,1)
                    +@re
                ,@i=@i-1
       -- return('0x'+@re)
        return @re
    end
    
    GO
--==============================================
--  FUNCTION  hexstr2varbin
--  将 varchar 类型的数据转换为 varbinary 类型
--==============================================

IF OBJECT_ID ('dbo.hexstr2varbin') IS NOT NULL
    DROP FUNCTION dbo.hexstr2varbin
GO

CREATE function [dbo].[hexstr2varbin](
  @char varchar(8000)
)returns varbinary(8000)
as
begin
    declare @re varbinary(8000), @tempchar varchar(2), 
            @getchar varchar(1), @getint int, @n int, @totalint int,
            @i int, @tempint int, @runNum int -- 字符串截取段数

     select @tempchar='',@i=datalength(@char), @re=0x; 

    if( @i>0)
    begin
        if ( @i%2 = 0) set @runNum= @i/2
        else set @runNum= @i/2 + 1 

        while (@runNum > 0)
        begin
            if(@runNum = 1) set @tempchar = @char 
            else set @tempchar = substring(@char, (@runNum-1)*2,2)

            select @n=1,@totalint=0;
            
            -- 循环处理截取的每个字符串 (这里的字符串长度为2)
            while @n < ( datalength(@tempchar) + 1 )
            begin
                set @getchar=substring(@tempchar,@n,1);

                -- 将字符转换为十六进制对应的数字
                select @getint=case  
                       when @getchar='a' then 10 
                       when @getchar='b' then 11
                       when @getchar='c' then 12 
                       when @getchar='d' then 13
                       when @getchar='e' then 14 
                       when @getchar='f' then 15
                       else  convert(int,@getchar) end;

                set @tempint=@getint*power(16,datalength(@tempchar)-@n)
                set @totalint = @totalint + @tempint
                set @n=@n+1
            end 

               set @re=convert(varbinary(1),@totalint) + @re;    
               set @runNum=@runNum-1;         
        end
    end
   return @re

end
GO

 

posted @ 2015-10-21 16:23  bobo-bobo  阅读(3676)  评论(0编辑  收藏  举报