How to convert a varbinary value as varchar

  • Hi,

    I need to convert the display representation of a varbinary value as varchar. e.g., the result of

    SELECT CAST(0x41 AS varbinary)

    can be converted and assigned to a varchar variable with value of '0x41' instead of 'A'.

    Could anyone help me how to do that?

    Thanks

    Bill

  • This is in BOL (acdata.chm::/ac_8_qd_14_8k6m.htm):

    CREATE PROCEDURE sp_hexadecimal

    @binvalue varbinary(255),

    @hexvalue varchar(255) OUTPUT

    AS

    DECLARE @charvalue varchar(255)

    DECLARE @i int

    DECLARE @length int

    DECLARE @hexstring char(16)

    SELECT @charvalue = '0x'

    SELECT @i = 1

    SELECT @length = DATALENGTH(@binvalue)

    SELECT @hexstring = '0123456789abcdef'

    WHILE (@i <= @length)

    BEGIN

    DECLARE @tempint int

    DECLARE @firstint int

    DECLARE @secondint int

    SELECT @tempint = CONVERT(int, SUBSTRING(@binvalue,@i,1))

    SELECT @firstint = FLOOR(@tempint/16)

    SELECT @secondint = @tempint - (@firstint*16)

    SELECT @charvalue = @charvalue +

    SUBSTRING(@hexstring, @firstint+1, 1) +

    SUBSTRING(@hexstring, @secondint+1, 1)

    SELECT @i = @i + 1

    END

    SELECT @hexvalue = @charvalue

    --Jonathan



    --Jonathan

  • Thanks, Jonathan

    That's great.

    Bill

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply