数字系统转换 - 仅使用SQL语句将基数10作为基数x

时间:2013-09-07 00:34:13

标签: sql oracle oracle11g base-conversion

我想要stop making the same performance mistakes并且在这个问题上需要比我更稳定的SQL语句。

基本上我想要function

create or replace FUNCTION SEQGEN(vinp in varchar2, iSeq in INTEGER) 
RETURN VARCHAR2 is vResult VARCHAR2(32);
  iBas INTEGER; iRem INTEGER; iQuo INTEGER; lLen CONSTANT INTEGER := 2;
BEGIN
  iBas := length(vInp);
  iQuo := iSeq;
  WHILE iQuo > 0 LOOP
    iRem := iQuo mod iBas;
    --dbms_output.put_line('Now we divide ' || lpad(iQuo,lLen,'0') || ' by ' || lpad(iBas,lLen,'0') || ', yielding a quotient of ' || lpad( TRUNC(iQuo / iBas) ,lLen,'0') || ' and a remainder of ' || lpad(iRem,lLen,'0') || ' giving the char: ' || substr(vInp, iRem, 1)); end if;
    iQuo := TRUNC(iQuo / iBas);
    If iRem < 1 Then iRem := iBas; iQuo := iQuo - 1; End If;
    vResult := substr(vInp, iRem, 1) || vResult;
  END LOOP;
  RETURN vResult;
END SEQGEN;

仅用SQL语句编写。

类似的东西:

WITH sequence ( vResult, lSeq ) AS 
(
  SELECT str, length(str) base FROM (SELECT 'abc' str FROM DUAL)

)
SELECT vResult FROM sequence WHERE lSeq < 13

if str = 'aB' output:           if str = 'abC' output:
1               a                       a
2               B                       b
3           a   a                       C
4           a   B                   a   a
5           B   a                   a   b
6           B   B                   a   C
7       a   a   a                   b   a
8       a   a   B                   b   b
9       a   B   a                   b   C
10      a   B   B                   C   a
11      B   a   a                   C   b
12      B   a   B                   C   C
13      B   B   a               a   a   a

如果str ='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'则:

SELECT vResult FROM sequence 
WHERE vResult in ('0001','0002','0009','000A','000Z',
                  '0010','0011','001A','ZZZZ')  --you get the idea...

我在Stackoverflow上发现了一些相关的问题。 Base 36 to Base 10 conversion using SQL onlyPL/SQL base conversion without functions。 但凭借我目前对SQL的了解,我无法破解这个......


EDITED


或者,它几乎就像这个:

select sum(position_value) pos_val from (
  select power(base,position-1) * instr('abc', digit) as position_value from (
    select substr(input_string,length(input_string)+1-level,1) digit, level position, length(input_string) base
      from (select 'cc' input_string from dual)
      connect by level <= length(input_string)
  )
)

异常我想把pos_val作为参数并输出input_string ...

1 个答案:

答案 0 :(得分:-1)

Here is one way. Oracle SQL中模型函数的另一个很酷的用途。