Skip to main content

Converting string data to hex. Cannot cast varchar to varbinary

  • January 25, 2018
  • 2 replies
  • 16 views

dcanadillas
Forum|alt.badge.img+1

Hi everyone,

I have a prospect that wants to replicate in Vertica the hex() function included in their current db (Infobright, that uses this same function as mysql) and they are trying to convert strings to hexadecimal from a varchar column.

I thought that using our "to_hex" function could do it, but it seems that we only support number input. But I found something interesting.

If I do "select to_hex('string'::varbinary);" it works. But if the string is selected from a varchar column it cannot cast the variable (we cannot cast varchar to binary or varbinary). Here is an example executed from my vsql:

dbadmin=> select node_name from nodes;

node_name

v_vmart_node0001
(1 row)

dbadmin=> select to_hex('v_vmart_node0001'::varbinary);

to_hex

765f766d6172745f6e6f646530303031
(1 row)

dbadmin=> select to_hex(node_name::varbinary) from nodes;
ERROR 2366: Cannot cast type varchar to varbinary

Would be an easy way to convert a string from a varchar column to hexadecimal without developing a UDx?

Thanks!

Best regards,
David.

2 replies

Jim_Knicely
Forum|alt.badge.img+2
  • Participating Frequently
  • January 25, 2018

Hi,

This seems to work okay...

dbadmin=> \df to_hex;
                         List of functions
 procedure_name | procedure_return_type | procedure_argument_types
----------------+-----------------------+--------------------------
 to_hex         | Long Varchar          | Long Varbinary
 to_hex         | Varchar               | Integer
 to_hex         | Varchar               | Varbinary
(3 rows)

dbadmin=> select to_hex((node_name::Long Varchar)::Long Varbinary) from nodes;
             to_hex
--------------------------------
 765f736664635f6e6f646530303031
(1 row)

See:
https://my.vertica.com/docs/9.0.x/HTML/index.htm#Authoring/SQLReferenceManual/DataTypes/DataTypeCoercionChart.htm


dcanadillas
Forum|alt.badge.img+1
  • Author
  • Participating Frequently
  • January 25, 2018

Thank you Jim!

I see! So because long varchar can be explicitly coerced to long varbinary, you can do it by converting varchar to long varchar... That does the trick!!

It works! Thanks!

Best regards,
David.