I need Oracle SQL function which sums comma separated values.
For example, this function needs to return 100 from string:
0,4,2,88,6
I need Oracle SQL function which sums comma separated values.
For example, this function needs to return 100 from string:
0,4,2,88,6
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;
A pure PL/SQL solution:
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;
/
Query:
SELECT SUM_SPLIT_STRING( '0,4,2,88,6' ) AS sum FROM DUAL;
Output:
SUM
---
100
a solution without regular expressions:
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
There is no Oracle function that does this out of the box. In SQL, you can maybe use a pivot table to split the string into numbers
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