Onega

a lot of VC++ posts, a few C# posts, and some miscellaneous stuff

Saturday, February 11, 2006

binary to string in SQLServer

convert 0x1234 to "1234"
CREATE FUNCTION [dbo].[hexdecimal] (@binvalue varbinary(255))
RETURNS varchar(255) AS
BEGIN

DECLARE @hexvalue varchar(255)
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 = substring(@charvalue,3, len(@charvalue)-2)
RETURN @hexvalue

END

--There are undocumented procedures: xp_varbintohexstr and master.dbo.fn_varbintohexstr

0 Comments:

Post a Comment

<< Home