在Oracle SQL中以逗号分隔值

时间:2016-02-24 12:02:29

标签: sql oracle

我需要Oracle SQL函数,它将逗号分隔值相加。

例如,此函数需要从string:

返回100
0,4,2,88,6

4 个答案:

答案 0 :(得分:3)

纯PL / SQL解决方案:

CREATE OR REPLACE FUNCTION sum_split_String(
  i_str    IN  VARCHAR2,
  i_delim  IN  VARCHAR2 DEFAULT ','
) RETURN NUMBER DETERMINISTIC
AS
  p_sum          NUMBER := 0;
  p_start        NUMBER(5) := 1;
  p_end          NUMBER(5);
  c_len CONSTANT NUMBER(5) := LENGTH( i_str );
  c_ld  CONSTANT NUMBER(5) := LENGTH( i_delim );
BEGIN
  IF i_str IS NULL THEN
    RETURN NULL;
  END IF;
  p_end := INSTR( i_str, i_delim, p_start );
  WHILE p_end > 0 LOOP
    p_sum := p_sum + TO_NUMBER( SUBSTR( i_str, p_start, p_end - p_start ) );
    p_start := p_end + c_ld;
    p_end := INSTR( i_str, i_delim, p_start );
  END LOOP;
  IF p_start <= c_len + 1 THEN
    p_sum := p_sum + TO_NUMBER( SUBSTR( i_str, p_start, c_len - p_start + 1 ) );
  END IF;
  RETURN p_sum;
END;
/

<强>查询

SELECT SUM_SPLIT_STRING( '0,4,2,88,6' ) AS sum FROM DUAL;

<强>输出

SUM
---
100

答案 1 :(得分:2)

select sum(regexp_substr('0,4,2,88,6', '[^,]+', 1, level)) as result
from dual
connect by regexp_substr('0,4,2,88,6', '[^,]+', 1, level) is not null;

答案 2 :(得分:1)

没有正则表达式的解决方案:

create or replace function calc(i_str in varchar2)
  return number is l_result number;
begin
  execute immediate 'select ' || i_str || ' from dual'
    into l_result;
  return l_result;
exception
  when others then
    return null;
end;

select calc(replace('0,4,2,88,6', ',', '+')) from dual
--> 100

答案 3 :(得分:0)

没有开箱即用的Oracle功能。 在SQL中,您可以使用数据透视表将字符串拆分为数字

with MyString  as
 (select '0,4,2,88,6' Str from dual
  )
,pivot as (
  Select Rownum Pnum
  From dual
  Connect By Rownum <= 100   
  )
SELECT sum(to_number(REGEXP_SUBSTR (ms.Str,'[^,]+',1,pv.pnum))) Num
  FROM MyString ms
      ,pivot pv
where REGEXP_SUBSTR (ms.Str,'[^,]+',1,pv.pnum) is not null