Converting a String to HEX in SQL

若如初见. 提交于 2019-11-27 09:15:58
stephenbayer

Can you use Cast and the fn_varbintohexstr?

SELECT master.dbo.fn_varbintohexstr(CAST(SomeStringColumn AS varbinary)) 
FROM SomeTable

I'm not sure if you have that function in your database system, it is in MS-SQL.

I just tried it in my SQL server MMC on one of my tables:

SELECT     master.dbo.fn_varbintohexstr(CAST(Addr1 AS VARBINARY)) AS Expr1
FROM         Customer

This worked as expected. possibly what I know as master.dbo.fn_varbintohexstr on MS-SQL, might be similar to informix hex() function, so possibly try:

SELECT     hex(CAST(Addr1 AS VARBINARY)) AS Expr1
FROM         Customer

If it is possible for you to do this in the database client in code it might be easier.

Otherwise the error probably means that the built in hex function can't work with your values as you expect. I would double check the input value is trimmed and in the format first, it might be that simple. Then I would consult the database documentation that describes the hex function and see what its expected input would be and compare that to some of your values and find out what the difference is and how to change your values to match that of the expected input.

A simple google search for "informix hex function" brought up the first result page with the sentence: "Must be a literal integer or some other expression that returns an integer". If your data type is a string, first convert the string to an integer. It looks like at first glance you do something with the cast function (I am not sure about this).

select hex(cast SomeStringColumn as int)) from SomeTable

what about:

declare @hexstring varchar(max);
set @hexstring = 'E0F0C0';
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)

I saw this here: http://blogs.msdn.com/b/sqltips/archive/2008/07/02/converting-from-hex-string-to-varbinary-and-vice-versa.aspx

Sorrry, that work only on >MS SQL 2005

OLD Post but in my case I also had to remove the 0x part of the hex so I used the below code. (I'm using MS SQL)

convert(varchar, convert(Varbinary(MAX), YOURSTRING),2)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!