Getting Started with ASP.NET MVC - Part 6: ASP.NET MVC and Entity Framework
First Time? You can support us by signing up. It takes only 5 seconds. Click here to sign up. If you already have an account, click here to login.


Upload Image Close it
Select File

Learned something today? Share it, or learn from what others have learned today

hexstring to varbinary and vice versa

Feb 19 2012 12:00AM by vanne040   

Learned today that converting hexadecimal values to varbinary and vice versa is easier in SQL Server 2008 compared to SQL Server 2005. MS made life simpler with SQL 2K8 :) See below.

declare @hexstring varchar(max);

set @hexstring = '0xabcedf012439';

select CONVERT(varbinary(max), @hexstring, 1);

set @hexstring = 'abcedf012439';

select CONVERT(varbinary(max), @hexstring, 2);

go

declare @hexbin varbinary(max);

set @hexbin = 0xabcedf012439;

select CONVERT(varchar(max), @hexbin, 1), CONVERT(varchar(max), @hexbin, 2);

go

In SQL Server 2005, we had to use the XQuery functionality.

-- Convert hexstring value in a variable to varbinary:

declare @hexstring varchar(max);

set @hexstring = 'abcedf012439';

select cast('' as xml).value('xs:hexBinary( substring(sql:variable("@hexstring"), sql:column("t.pos")) )', 'varbinary(max)')

from (select case substring(@hexstring, 1, 2) when '0x' then 3 else 0 end) as t(pos)

go

-- Convert binary value in a variable to hexstring:

declare @hexbin varbinary(max);

set @hexbin = 0xabcedf012439;

select '0x' + cast('' as xml).value('xs:hexBinary(sql:variable("@hexbin") )', 'varchar(max)');

go

Other useful links

http://decipherinfosys.wordpress.com/2008/06/11/converting-a-hex-string-to-a-varbinary-or-vice-versa/ http://www.sqlusa.com/bestpractices2005/hexadecimal/

Read More..  [7 clicks]


vanne040
98 · 2% · 457
6
 
1
 
 
0
Incorrect
 
0
Interesting
 
 
0
Move



Submit

1  Comments  

  • The following code allowed me to do the hex conversion for one row/field at a time in SQL 2000.

    DECLARE @TestString VARCHAR(30), @Bin VARBINARY(255)
    
    SELECT @TestString = RTRIM(SomeCharColumn)
    FROM DB..Table (NOLOCK)
    WHERE ...
    
    PRINT @TestString
    SET @Bin = CONVERT(VARBINARY(255), @TestString)
    PRINT @Bin
    

    @Bin will print as HEX.

    commented on Feb 21 2012 1:12PM  .  Report Abuse This post is not formatted correctly
    Dave Vroman
    223 · 1% · 146

Your Comment


Sign Up or Login to post a comment.

"hexstring to varbinary and vice versa" rated 5 out of 5 by 6 readers
hexstring to varbinary and vice versa , 5.0 out of 5 based on 6 ratings
    Copyright © Beyondrelational.com Contact us      Privacy Policy      Terms of use      Report Abuse      Advertising