GBase 8s自定义使用hex或者unhex函数
从mysql迁移到GBase 8s数据库时,原有hex(有同名函数,但用法不同)、unhex函数在GBase 8s中不可用,因此需要自己创建相应的函数,可以使用C或者JAVA创建自定义例程,也可以使用存储过程。以下以存储过程方式创建。
hexstr函数实现的功能是:将文本转换成十六进制字符串显示。
unhex函数实现的功能是:将十六进制字符串转换成对应的ASCII可视文本显示。
-- hexstr
drop function if exists hexstr;
create function hexstr(pstr varchar(128))
returns varchar(254) with (not variant)
define curpos smallint;
define curval smallint;
define tmpstr varchar(254);
on exception
return null;
end exception;
let tmpstr = "";
for curpos = 1 to length(pstr)
let curval = ascii(substr(pstr,curpos,1));
let tmpstr = tmpstr || substr(hex(curval),9);
end for;
return tmpstr;
end function;
-- unhex
drop function if exists unhex;
create function unhex(pstr varchar(254))
returns varchar(128) with (not variant)
define curpos smallint;
define curval smallint;
define tmpint smallint;
define tmpstr varchar(128);
on exception
return null;
end exception;
let tmpint = 0;
let tmpstr = "";
for curpos = 1 to length(pstr)
let curval = 0;
case lower(substr(pstr,curpos,1))
when 'a' then let curval = 10;
when 'b' then let curval = 11;
when 'c' then let curval = 12;
when 'd' then let curval = 13;
when 'e' then let curval = 14;
when 'f' then let curval = 15;
else let curval = substr(pstr,curpos,1);
end case;
if mod(curpos,2) = 1 then
let tmpint = curval * 16;
else
let tmpint = tmpint + curval;
let tmpstr = tmpstr || chr(tmpint);
end if;
end for;
return tmpstr;
end function;
示例:
select unhex('4742617365203873') from dual;
select hexstr('GBase 8s') from dual;
得到的结果如下:
|(expression) |
|-------------|
|GBase 8s |
| (expression) |
|----------------|
|4742617365203873|