Converting a String to HEX in SQL

后端 未结 5 1313
孤城傲影
孤城傲影 2020-12-01 21:34

I\'m looking for a way to transform a genuine string into it\'s hexadecimal value in SQL. I\'m looking something that is Informix-friendly but I would obviously prefer somet

相关标签:
5条回答
  • 2020-12-01 22:01

    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
    
    0 讨论(0)
  • 2020-12-01 22:11

    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)

    0 讨论(0)
  • 2020-12-01 22:13

    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

    0 讨论(0)
  • 2020-12-01 22:20

    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
    
    0 讨论(0)
  • 2020-12-01 22:20

    The following works in Sql 2005.

    select convert(varbinary, SomeStringColumn) from SomeTable
    
    0 讨论(0)
提交回复
热议问题