日期:2014-05-17  浏览次数:21114 次

如何实现查询语句中减1的操作,具体请进
我有一个字段是由英文和字母组成的,如:BA12345或是1122AF,在查询中,我需要做的是得到BA12345减1后的数,即为BA12344,同样,1122AF减1得到1122AE

有没有什么办法用SQL能够实现这个

------解决方案--------------------
SQL> select substr(name,1,length(name)-1)||chr(ascii(substr(name,-1)) -1)
2 from test where id in (12,13);

SUBSTR(NAME,1,LENGTH(NAME)-1)||CHR(ASCII(S
------------------------------------------
hl2321
12hhic

SQL> select name from test where id in(12,13);

NAME
--------------------
hl2322
12hhid

SQL>
------解决方案--------------------
写一个函数,就方便在一个SQL语句中使用了.
create or replace function mySub(str varchar2) return varchar2
is
sstr varchar2(16);
ilen integer;
itemp integer;
ichar varchar2(1);
begin
ilen:=length(str);
sstr:= ' ';
for i in 0..ilen loop
ichar:=substr(str,ilen-i,1);
itemp:=i;
if ascii(ichar)> =ascii( '0 ') and ascii(ichar) <=ascii( '9 ') then
sstr:=concat(ichar,sstr);
else
exit;
end if;
end loop;
sstr:=to_char(to_number(sstr)-1);
sstr:=concat(substr(str,ilen-itemp,length(str)-length(sstr)),sstr);
return sstr;
end;

--测试: select mySub( 'a001 ') from dual;
------解决方案--------------------
转换成10进制,再减,再转换成16进制

-----十六进制转换十进制-----------------
  select sum(data1)
   from (select (CASE upper(substr( '1122AF ', rownum, 1))
   WHEN 'A ' THEN '10 '
   WHEN 'B ' THEN '11 '
   WHEN 'C ' THEN '12 '
   WHEN 'D ' THEN '13 '
   WHEN 'E ' THEN '14 '
   WHEN 'F ' THEN '15 '
   ELSE substr( '1122AF ', rownum, 1)
   END) * power(16, length( '1122AF ') - rownum) data1
   from dual
   connect by rownum <= length( '1122AF '))