Split multi column semicolon separated string and create records - sql

I have a stored procedure which receives three string parameters
1. p_ReqIDs VARCHAR2
2. p_ItemIDs VARCHAR2
3. p_Qtys VARCHAR2
The above 3 string variables contain semicolon-separated values like this:
p_ReqIDs := "56;56;56;"
p_ItemIDs := "3;2;1;"
p_Qtys := "400;300;200;"
I need to split values and create rows like this:
p_ReqIDs p_ItemIDs p_Qtys
------------------------------------
56 3 400
56 2 300
56 1 200
I need the query which splits and insert into table also.
Thanks

You could process parameters as follows:
SQL> declare
2 type l_rec_type is record(
3 r_ReqIDs varchar2(31),
4 r_ItemIDs varchar2(31),
5 r_Qtys varchar2(31)
6 );
7
8 type l_rec_list is table of l_rec_type;
9 -- your parameters.
10 l_ReqIDs constant varchar2(31) := '56;56;56;';
11 l_ItemIDs constant varchar2(31) := '3;2;1;';
12 l_Qtys constant varchar2(31) := '400;300;200;';
13
14 l_rec l_rec_list;
15 begin
16
17 with Parameters(param) as(
18 select l_ReqIDs from dual union all
19 select l_ItemIDs from dual union all
20 select l_Qtys from dual
21 ),
22 Occurrences(oc) as(
23 select level
24 from ( select max(regexp_count(param, '[^;]+')) moc
25 from parameters) s
26 connect by level <= s.moc
27 )
28 select max(res1)
29 , max(res2)
30 , max(res3)
31 bulk collect into l_rec
32 from (select decode(param, l_ReqIDs, res) res1
33 , decode(param, l_ItemIDs,res) res2
34 , decode(param, l_Qtys, res) res3
35 , rn
36 from ( select param, regexp_substr(param, '[^;]+', 1, o.oc) res
37 , row_number() over(partition by param order by param) rn
38 from parameters p
39 cross join occurrences o
40 )
41 )
42 group by rn;
43
44 for i in l_rec.first..l_rec.last
45 loop
46 dbms_output.put_line(l_rec(i).r_ReqIDs || ' ' || l_rec(i).r_ItemIDs || ' ' || l_rec(i).r_Qtys);
47 end loop;
48 end;
49 /
56 2 200
56 1 300
56 3 400
PL/SQL procedure successfully completed
If you need to just insert processed data into a table the only insert into statement and query will be needed (bulk collect into l_rec must be removed):
insert into your_table(<<columns>>)
with Parameters(param) as(
select l_ReqIDs from dual union all
select l_ItemIDs from dual union all
select l_Qtys from dual
....
-- the rest of the query from the above pl/sql block.
You also can insert an entire record into a table(in a case you need to do extra processing of extracted elements before insertion) as follows:
If number of columns in a table equal to number of elements being inserted
for i in l_rec.first..l_rec.last
loop
insert into your_table
values l_rec(i);
end loop;
If number of columns in a table is greater then the number of values being inserted
for i in l_rec.first..l_rec.last
loop
insert into (select column1, .. ,columnn from your_table)
values l_rec(i);
end loop;

i did like this :) short and sweet.
create or replace procedure proc1(p_ReqID varchar2,p_ItemID varchar2,p_ItemQty varchar2)
is
begin
insert into test(req_id,item_id,itemqty)
select regexp_substr(req_id,'[^;]+',1,level),
regexp_substr(item_id,'[^;]+',1,level),
regexp_substr(item_qty,'[^;]+',1,level)
from (
select p_ReqID Req_ID,p_ItemID item_id,p_ItemQty item_qty
from dual
)
connect by regexp_substr(req_id,'[^;]+',1,level) is not null;
end;

Related

Count specific letters in string

I got a question how to get number of characters from a string ?
In this scenario we got string: 'pppeerskka' and the outcome should look like '3p2e1r1s2k1a'
and the outcome should look like '3p2e1r1s2k1a'
One option is to split the input string into rows, apply count function to it (so that you'd know how many different letters you have), and - finally - aggregate them back using listagg.
SQL> with test (col) as
2 (select 'pppeerskka' from dual),
3 temp as
4 (select substr(col, level, 1) letter,
5 count(*) cnt,
6 max(level) lvl
7 from test
8 connect by level <= length(col)
9 group by substr(col, level, 1)
10 )
11 select listagg(cnt || letter, '') within group (order by lvl) result
12 from temp;
RESULT
--------------------------------------------------------------------------------
3p2e1r1s2k1a
SQL>
Converting it into a function is a simple task:
SQL> create or replace function f_count (par_string in varchar2)
2 return varchar2
3 is
4 retval varchar2(30);
5 begin
6 with temp as
7 (select substr(par_string, level, 1) letter,
8 count(*) cnt,
9 max(level) lvl
10 from test
11 connect by level <= length(par_string)
12 group by substr(par_string, level, 1)
13 )
14 select listagg(cnt || letter, '') within group (order by lvl)
15 into retval
16 from temp;
17
18 return retval;
19 end;
20 /
Function created.
SQL> select f_count('pppeerskka') result from dual;
RESULT
--------------------------------------------------------------------------------
3p2e1r1s2k1a
SQL>

Oracle function return table

I don't know what is best solution for my problem. I need function with one parameter which resault is
VAL
-----
1
2
3
In function I need put union all to get all value.
Select column_1 as VAL from my_table where id = P_FUNCTION_PARAMETER --return 1
union all
Select column_2 as VAL from my_table where id = P_FUNCTION_PARAMETER --return 2
union all
Select column_3 as VAL from my_table where id = P_FUNCTION_PARAMETER; --return 3
What is the best solution for this?
"Best" just depends. Return a ref cursor or a collection, whichever you prefer.
For example:
SQL> create or replace function f_test_rc
2 return sys_refcursor
3 is
4 rc sys_refcursor;
5 begin
6 open rc for
7 select 1 from dual union all
8 select 2 from dual union all
9 select 3 from dual;
10
11 return rc;
12 end;
13 /
Function created.
SQL> select f_test_rc from dual;
F_TEST_RC
--------------------
CURSOR STATEMENT : 1
CURSOR STATEMENT : 1
1
----------
1
2
3
SQL> create or replace function f_test_coll
2 return sys.odcinumberlist
3 as
4 l_coll sys.odcinumberlist;
5 begin
6 select * bulk collect into l_coll
7 from (select 1 from dual union all
8 select 2 from dual union all
9 select 3 from dual
10 );
11
12 return l_coll;
13 end;
14 /
Function created.
SQL> select * from table(f_test_coll);
COLUMN_VALUE
------------
1
2
3
SQL>
First let's set up a small table for testing:
create table my_table
( id number primary key
, column_1 number
, column_2 number
, column_3 number
);
insert into my_table
select 1008, 3, -8, 0.2 from dual union all
select 1002, 6, null, -1.2 from dual
;
commit;
The function can look like this. Note that I don't use union all - that will require reading the table three times, when only one time is enough.
create or replace function my_function (p_function_parameter number)
return sys.odcinumberlist
as
arr sys.odcinumberlist;
begin
select case ord when 1 then column_1
when 2 then column_2
when 3 then column_3 end
bulk collect into arr
from my_table cross join
(select level as ord from dual connect by level <= 3)
where id = p_function_parameter
order by ord
;
return arr;
end;
/
The function could be used, for example, like this: (in older versions you may need to wrap the function call within the table operator)
select * from my_function(1002);
COLUMN_VALUE
------------
6
-1.2

Function PL/SQL ORACLE

I need to do a function with the following sql
This sql converts from numbers to letters
With
Numero as (
select 3 N from dual
)
,
PreProcesado1 as (
select N
, floor(mod(N, 10)) Unidades
from Numero
)
select N, case Unidades
when 0 then ''
when 1 then 'one'
when 2 then 'two'
when 3 then 'three'
when 4 then 'four'
when 5 then 'five'
when 6 then 'six'
when 7 then 'seven'
when 8 then 'eight'
when 9 then 'nine'
end
end
from PreProcesado1;
I’m doing it like this but it doesn’t work, must have an input parameter which in this case is entry_numero and which should be converted
create or replace function fun_departamento(entry_numero number)
return varchar2 is
response varchar2(120);
begin
With
Numero as (
select entry_numero N from dual
)
,
PreProcesado1 as (
select N
, floor(mod(N, 10)) Unidades
from Numero
)
select N, case Unidades
when 0 then ''
when 1 then 'one'
when 2 then 'two'
when 3 then 'three'
when 4 then 'four'
when 5 then 'five'
when 6 then 'six'
when 7 then 'seven'
when 8 then 'eight'
when 9 then 'nine'
end
end
into response
from PreProcesado1;
return response;
end;
/
I get this error, I'd appreciate your help
PL/SQL: SQL Statement ignored
PL/SQL: ORA-00947: not enough values
This is a simpler way to do what you need:
to_char( to_date(n,'J'),'jsp')
For example:
SQL> select to_char( to_date(4,'J'),'jsp') as n from dual;
N
----------
four
Notice that this does not handle 0, so you may need:
select
case
when n != 0 then to_char( to_date(n,'J'),'jsp')
end
from ...
Here you find something more.
As you said that you want to do it your way, then see lines #16 and #29 as
line 16: you're selecting two values (N and CASE expression)
line 29: you're trying to put 2 values into a single variable (response)
Therefore, remove N from line #16 (or add another variable to insert into).
SQL> create or replace function fun_departamento(entry_numero number)
2 return varchar2 is
3 response varchar2(120);
4 begin
5 With
6 Numero as (
7 select entry_numero N from dual
8 )
9 ,
10 PreProcesado1 as (
11 select N
12 , floor(mod(N, 10)) Unidades
13 from Numero
14 )
15 select
16 -- N, --> without it! ...
17 case Unidades
18 when 0 then ''
19 when 1 then 'one'
20 when 2 then 'two'
21 when 3 then 'three'
22 when 4 then 'four'
23 when 5 then 'five'
24 when 6 then 'six'
25 when 7 then 'seven'
26 when 8 then 'eight'
27 when 9 then 'nine'
28 end
29 into response --> ... as you're inserting into a single variable
30 from PreProcesado1;
31 return response;
32 end;
33 /
Function created.
Testing:
SQL> select fun_departamento(5) from dual;
FUN_DEPARTAMENTO(5)
--------------------------------------------------------------------------------
five
SQL>

Oracle SQL running total on change of field (SUM on column only when field changes)

I have a question in regards to how to SUM on a column only when a field is changing.
Take for example the table below:
Note that Column A and Column B are different tables. I.e. A was selected from Table X and B was selected from Table Y
SELECT X.A, Y.B
FROM X
INNER JOIN Y ON X.DATE = Y.DATE AND X.VAL1 =
Y.VAL1 AND X.VAL2 = Y.VAL2
A B
123 5
123 5
456 10
789 15
789 15
I need to sum column B on change of field on column A:
I.e. the query should return 5 + 10 + 15 = 30 (5 the first time because value in column A is 123, 10 the second time because column A changed from 123 to 456 - note that the second row was skipped because column A still contains value 123 - hence the change of field logic and so on).
I can't do a simple SUM(B) because that would return 50. I also cannot do SUM(B) OVER (PARTITION BY A) because that would do a running total by group, not by change of field.
My output needs to look like this:
A B X
123 5 5
123 5 5
456 10 15
789 15 30
789 15 30
I am trying to do this within a simple query. Is there a particular function I can use to do this?
For the simple data set provided, the following should work. You will, of course, want to review the ORDER BY clauses for correctness in your exact use case.
SELECT a
,b
,SUM(CASE WHEN a = prev_a THEN 0 ELSE b END) OVER (ORDER BY a RANGE UNBOUNDED PRECEDING) AS x
FROM (
SELECT a
,b
,LAG(a) OVER (ORDER BY a) AS prev_a
FROM {your_query}
)
This solution makes use of the LAG function, which returns the specified column from the previous result. Then the outer query's SUM gives the value only when the previous row didn't have the same value. And there is also the windowing clause involved in the SUM because you specified that you needed a running total.
Ta-daaa?
SQL> with test (a, b) as
2 (select 123, 5 from dual union all
3 select 123, 5 from dual union all
4 select 456, 10 from dual union all
5 select 789, 15 from dual union all
6 select 789, 15 from dual
7 ),
8 proba as(
9 select a, b,
10 case when a <> nvl(lag(a) over (order by a), 0) then 'Y' else 'N' end switch
11 from test
12 )
13 select a, b,
14 sum(decode(switch, 'Y', b, 0)) over (partition by null order by a) x
15 from proba
16 order by a;
A B X
---------- ---------- ----------
123 5 5
123 5 5
456 10 15
789 15 30
789 15 30
SQL>
you can also create a function and use it, see sample below,
create package test_pkg123
as
a number;
r_sum NUMBER;
function get_r_sum(p_a number, p_val NUMBER, rown NUMBER) return number;
end;
/
create or replace package body test_pkg123
as
function get_r_sum(p_a number, p_val NUMBER, rown NUMBER) return number
is
begin
if rown = 1 then
r_sum := p_val;
return r_sum;
end if;
if p_a != a then
r_sum := nvl(r_sum, 0) + nvl(p_val, 0);
end if;
a := p_a;
return r_sum;
end;
end;
/
with test (a, b) as
(select 123, 5 from dual union all
select 123, 5 from dual union all
select 456, 10 from dual union all
select 789, 15 from dual union all
select 789, 15 from dual union all
select 789, 15 from dual union all
select 123, 2 from dual
)
select a, b, test_pkg123.get_r_sum(a, b, rownum) r_sum
from test;
Output:
A B R_SUM
123 5 5
123 5 5
456 10 15
789 15 30
789 15 30
789 15 30
123 2 32
7 rows selected

How to get comparison operator from string to where clause

I have data in reference table like <55, >60 (etc) and in source the values will come 40, 70 (etc). So based on reference values I have to check condition.
Example ;
if the value reference table is <55
my condition in where clause would be 40<55
if it is >70
my condition in where clause would be
40>60
actaully I am checking multipule condition on different fileds on where where .. this is going to be one of condition with AND.
Can you suggest me the way to handle it .
Thanks in advance
SQL> column str format A10;
SQL> WITH ref_data
2 AS (SELECT '<55' VAL
3 FROM dual
4 UNION ALL
5 SELECT '>60' val
6 FROM dual),
7 source_data
8 AS (SELECT 40 VAL
9 FROM dual
10 UNION ALL
11 SELECT 70 VAL
12 FROM dual)
13 SELECT CASE
14 WHEN B.val < To_number(Regexp_substr(A.val, '[[:digit:]]+')) THEN B.val
15 ||'<'
16 ||
17 Regexp_substr(A.val, '[[:digit:]]+')
18 ELSE B.val
19 ||'>'
20 ||Regexp_substr(A.val, '[[:digit:]]+')
21 END str
22 FROM ref_data A,
23 source_data b;
STR
----------
40<55
70>55
40<60
70>60
SQL>