CREATE FUNCTION dbo.BinToHex (
	@binvalue VARBINARY(255) )
RETURNS VARCHAR(255)
AS  
BEGIN 
	IF NOT @binvalue IS NULL
	BEGIN

		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

		RETURN @charvalue

	END
	
	RETURN '0x00'
END
