我在db2数据库中有一个字段,它是十六进制格式,即0x0a
十进制格式的数字10。十六进制字段的数据类型为char(1) for bit data
。
hex(myfield) gives me the hexadecimal 0A
如何在db2上的查询中将0x0a转换为10?
我试过了:cast(hex(myfield),integer)
和int(hex(myfield))
没有运气。
有可能吗?
答案 0 :(得分:2)
AFAIK,DB2中没有内置的单一功能可以执行转换,但有一个blog post showing how to define such a function。以下功能取自该文章:
--#SET TERMINATOR @
CREATE OR REPLACE FUNCTION HEX2INT(str VARCHAR(8))
RETURNS INTEGER
SPECIFIC HEX2INT
DETERMINISTIC NO EXTERNAL ACTION CONTAINS SQL
BEGIN ATOMIC
DECLARE res INTEGER DEFAULT 0;
DECLARE pos INTEGER DEFAULT 1;
DECLARE nibble CHAR(1);
WHILE pos <= LENGTH(str) DO
SET nibble = SUBSTR(str, pos, 1);
SET res = BITOR(CASE WHEN BITAND(res, 134217728) != 0
THEN BITOR(16 * BITANDNOT(res, 134217728),
-2147483648)
ELSE 16 * res END,
CASE nibble
WHEN '0' THEN 0
WHEN '1' THEN 1
WHEN '2' THEN 2
WHEN '3' THEN 3
WHEN '4' THEN 4
WHEN '5' THEN 5
WHEN '6' THEN 6
WHEN '7' THEN 7
WHEN '8' THEN 8
WHEN '9' THEN 9
WHEN 'A' THEN 10
WHEN 'a' THEN 10
WHEN 'B' THEN 11
WHEN 'b' THEN 11
WHEN 'C' THEN 12
WHEN 'c' THEN 12
WHEN 'D' THEN 13
WHEN 'd' THEN 13
WHEN 'E' THEN 14
WHEN 'e' THEN 14
WHEN 'F' THEN 15
WHEN 'f' THEN 15
ELSE RAISE_ERROR('78000', 'Not a hex string')
END),
pos = pos + 1;
END WHILE;
RETURN res;
END
@
--#SET TERMINATOR ;
所描述的各种转换操作还有更多功能。
答案 1 :(得分:1)
我相信你可以简化以下
WITH fred(x)AS(VALUES'f1'),
nurk (a) as (SELECT UPPER(substr(x,1)) from fred
union all
select UPPER(substr(a,2)) from nurk
where substr(a,1,1) <> ' '),
bare (b, c) as (select substr(a,1,1), (length(a) - 1)
from nurk),
trap (d) as ((SELECT (ASCII(B) - ASCII('7')) *
power(16,c)
FROM BARE
WHERE (B BETWEEN 'A' AND 'F')
and
c <> -1)
union
(SELECT (ASCII(B) - ASCII('0')) *
power(16,c)
FROM BARE
WHERE (B not BETWEEN 'A' AND 'F')
and
c <> -1))
从陷阱中选择总和(d)
以
运行db2 -f“上面的文件名”
给出
的结果241
尝试使用f1以外的值进行测试
John Hennesy
答案 2 :(得分:0)
在标准SQL中(我希望如此):
with inp (val) as
(values ('FF'), ('AB'), ('ABCDEF')),
calc(val, urval, res, f) as
(select case when length(val) > 1
then substr(val, 1, length(val)-1)
else '' end, val,
locate(right(val, 1),'0123456789ABCDEF')-1, 16
from inp
union all
select case when length(val) > 1
then substr(val, 1, length(val)-1)
else '' end, urval,
res + ((locate(right(val, 1),'0123456789ABCDEF')-1) * f),
f * 16
from calc
where length(val) > 0)
select urval, res
from calc
where val = ''
==&GT;
URVAL RES
FF 255
AB 171
ABCDEF 11.259.375
答案 3 :(得分:0)
convert(datatype,column_Name)
例如:转换(十进制(18,2),column_Name) --here column_Name具有十六进制值
答案 4 :(得分:-3)
语法如下
Count Column
--------------
0 TypeA
1 TypeB
1 TypeC
如果您需要有关转换为特定数据类型的更多详细信息,请查看以下文档
数据类型
https://technet.microsoft.com/en-us/library/ms187594(v=sql.105).aspx
转换数据类型
https://technet.microsoft.com/en-us/library/ms191530(v=sql.105).aspx