oracle select find specific values from array true or false - sql

I will try to explain this the best that I can, I have an array of products ['VALUE1','VALUE2']
my table has this data as an example
lets say the values are
product_id
order_qty
VALUE1
5
VALUE2
3
How can I build a select statement to check the table if product_id equals VALUE1 and VALUE2 but if the array contains VALUE3 it returns false else it's true I know using a function would be better.

This is how I understood it.
SQL> set serveroutput on;
Sample table:
SQL> select * from product;
PRODUC ORDER_QTY
------ ----------
VALUE1 5
VALUE2 3
PL/SQL code; it intersects values from the table with contents of collection. If that result is equal to number of values in collection, result is TRUE:
SQL> declare
2 l_arr sys.odcivarchar2list := sys.odcivarchar2list();
3 l_cnt number;
4 begin
5 l_arr.extend;
6 l_arr(1) := 'VALUE1';
7 l_arr.extend;
8 l_arr(2) := 'VALUE2';
9
10 select count(*)
11 into l_cnt
12 from (select product_id from product
13 intersect
14 select column_value
15 from table(l_arr)
16 );
17 dbms_output.put_line(l_cnt);
18 if l_cnt = l_arr.count then
19 dbms_output.put_line('Result is TRUE');
20 else
21 dbms_output.put_line('Result is FALSE');
22 end if;
23 end;
24 /
2
Result is TRUE
PL/SQL procedure successfully completed.
What if we add VALUE3 to collection? Result is then FALSE.
SQL> declare
2 l_arr sys.odcivarchar2list := sys.odcivarchar2list();
3 l_cnt number;
4 begin
5 l_arr.extend;
6 l_arr(1) := 'VALUE1';
7 l_arr.extend;
8 l_arr(2) := 'VALUE2';
9 l_arr.extend;
10 l_arr(3) := 'VALUE3';
11
12 select count(*)
13 into l_cnt
14 from (select product_id from product
15 intersect
16 select column_value
17 from table(l_arr)
18 );
19 if l_cnt = l_arr.count then
20 dbms_output.put_line('Result is TRUE');
21 else
22 dbms_output.put_line('Result is FALSE');
23 end if;
24 end;
25 /
Result is FALSE
PL/SQL procedure successfully completed.
SQL>

SELECT
CASE WHEN
COUNT(CASE WHEN PRODUCT_ID IN ('VALUE1','VALUE2') THEN 1 END) = COUNT(*)
THEN 'TRUE' ELSE 'FALSE'
END CHK
FROM T;
or you can just compare collections (NESTED TABLE):
create table t_product as
select 'VALUE1' product_id from dual union all
select 'VALUE2' product_id from dual union all
select 'VALUE3' product_id from dual;
declare
type string_table is table of t_product.product_id%type;
arr_input string_table:=string_table('VALUE1','VALUE2');
tab_data string_table;
begin
select product_id bulk collect into tab_data from t_product;
if tab_data = arr_input
then
dbms_output.put_line('yes');
else
dbms_output.put_line('no');
end if;
end;
/
Or:
select
case
when sys.ku$_vcnt('VALUE1','VALUE2') = X
then 'true'
else 'false'
end chk
from (select cast(collect(cast(product_id as varchar2(4000))) as sys.ku$_vcnt) x from t_product);
NB: it's better to create and use own type instead of sys.ku$_vcnt, for example:
create or replace type varchar2_table as table of varchar2(4000);

Related

Oracle VIEW showing when last records were created in my tables

I have tables t1 and t2 and both of them do have columns created_on containing the timestamp when each record was created. Usual thing.
Now I'd like to create the view which would show my tables and the timestamp of last created record (MAX(created_on)) in corresponding table.
The result should look like:
table | last_record
======+============
t1 | 10.05.2019
t2 | 12.11.2020
For example I can retrieve the list of my tables with:
SELECT * FROM USER_TABLES WHERE table_name LIKE 'T%'
I'd like to get the timestamp of last record for each of these tables.
How to create this view?
It might depend on tables' description; I presume they are somehow related to each other.
Anyway: here's how I understood the question. Read comments within code.
SQL> with
2 -- sample data
3 t1 (id, name, created_on) as
4 (select 1, 'Little', date '2021-12-14' from dual union all --> max for Little
5 select 2, 'Foot' , date '2021-12-13' from dual union all --> max for Foot
6 select 2, 'Foot' , date '2021-12-10' from dual
7 ),
8 t2 (id, name, created_on) as
9 (select 2, 'Foot' , date '2021-12-09' from dual union all
10 select 3, 'SBrbot', date '2021-12-14' from dual --> max for SBrbot
11 )
12 -- query you'd use for a view
13 select id, name, max(created_on) max_created_on
14 from
15 -- union them, so that it is easier to find max date
16 (select id, name, created_on from t1
17 union all
18 select id, name, created_on from t2
19 )
20 group by id, name;
ID NAME MAX_CREATE
---------- ------ ----------
1 Little 14.12.2021
2 Foot 13.12.2021
3 SBrbot 14.12.2021
SQL>
After you fixed the question, that's even easier; view query begins at line #12:
SQL> with
2 -- sample data
3 t1 (id, name, created_on) as
4 (select 1, 'Little', date '2021-12-14' from dual union all
5 select 2, 'Foot' , date '2021-12-13' from dual union all
6 select 2, 'Foot' , date '2021-12-10' from dual
7 ),
8 t2 (id, name, created_on) as
9 (select 2, 'Foot' , date '2021-12-09' from dual union all
10 select 3, 'SBrbot', date '2021-12-14' from dual
11 )
12 select 't1' source_table, max(created_on) max_created_on from t1
13 union
14 select 't2' source_table, max(created_on) max_created_on from t2;
SO MAX_CREATE
-- ----------
t1 14.12.2021
t2 14.12.2021
SQL>
If it has to be dynamic, one option is to create a function that returns ref cursor:
SQL> create or replace function f_max
2 return sys_refcursor
3 is
4 l_str varchar2(4000);
5 rc sys_refcursor;
6 begin
7 for cur_r in (select distinct c.table_name
8 from user_tab_columns c
9 where c.column_name = 'CREATED_ON'
10 order by c.table_name
11 )
12 loop
13 l_str := l_str ||' union all select ' || chr(39) || cur_r.table_name || chr(39) ||
14 ' table_name, max(created_on) last_updated from ' || cur_r.table_name;
15 end loop;
16
17 l_str := ltrim(l_str, ' union all ');
18
19 open rc for l_str;
20 return rc;
21 end;
22 /
Function created.
Testing:
SQL> select f_max from dual;
F_MAX
--------------------
CURSOR STATEMENT : 1
CURSOR STATEMENT : 1
TA LAST_UPDAT
-- ----------
T1 14.12.2021
T2 14.12.2021
SQL>
I have 30+ tables and wanted avoid hard coding SELECT statements for each of these tables and UNION them all. I expected some solution where I would insert tablenames in kinda array and create JOIN to show result with all last records. I know problem is here that tablename is variable!
You cannot do this in SQL as a VIEW is set at compile time and the tables must be known; the best you can do is to dynamically create an SQL statement in PL/SQL and then use EXECUTE IMMEDIATE and then re-run it if you want to recreate the view:
DECLARE
v_tables SYS.ODCIVARCHAR2LIST := SYS.ODCIVARCHAR2LIST(
'TABLE1', 'TABLE2', 'table3', 'TABLE5'
);
v_sql CLOB := 'CREATE OR REPLACE VIEW last_dates (table_name, last_date) AS ';
BEGIN
FOR i in 1 .. v_tables.COUNT LOOP
IF i > 1 THEN
v_sql := v_sql || ' UNION ALL ';
END IF;
v_sql := v_sql || 'SELECT '
|| DBMS_ASSERT.ENQUOTE_LITERAL(v_tables(i))
|| ', MAX(created_on) FROM '
|| DBMS_ASSERT.ENQUOTE_NAME(v_tables(i), FALSE);
END LOOP;
EXECUTE IMMEDIATE v_sql;
END;
/
Then for the sample tables:
CREATE TABLE table1 (created_on) AS
SELECT SYSDATE - LEVEL FROM DUAL CONNECT BY LEVEL <= 3;
CREATE TABLE table2 (created_on) AS
SELECT SYSDATE - LEVEL FROM DUAL CONNECT BY LEVEL <= 3;
CREATE TABLE "table3" (created_on) AS
SELECT SYSDATE - LEVEL FROM DUAL CONNECT BY LEVEL <= 3;
CREATE TABLE table5 (created_on) AS
SELECT SYSDATE FROM DUAL;
After running the PL/SQL block, then:
SELECT * FROM last_dates;
Outputs:
TABLE_NAME
LAST_DATE
TABLE1
2021-12-13 13:21:58
TABLE2
2021-12-13 13:21:59
table3
2021-12-13 13:21:59
TABLE5
2021-12-14 13:21:59
db<>fiddle here

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

SQL - Selecting only columns containing sum(data)

This are few records that I want to have sum of but excluding columns with NULL values:
ID val1 val2 val3
1 1 2
2 0 3
3 2 4
select
sum(val1),
sum(val2),
sum(val3)
from table
will result in:
val1 val2 val3
3 9
but I would prefer to see:
val2 val3
3 9
Is there anyway to achive that in SQL or PL/SQL?
kind regards
Sample data:
SQL> select * from test;
ID VAL1 VAL2 VAL3
---------- ---------- ---------- ----------
1 1 2
2 0 3
3 2 4
In my opinion, this is just fine:
SQL> select sum(val1), sum(val2), sum(val3) from test;
SUM(VAL1) SUM(VAL2) SUM(VAL3)
---------- ---------- ----------
3 9
SQL>
Why? Because what you prefer requires some programming and that doesn't have to be simple. Your example is simple, so something like this is easy as there are 6 possible combinations:
SQL> create or replace function f_test return sys_refcursor
2 is
3 l_sum1 number;
4 l_sum2 number;
5 l_sum3 number;
6 rc sys_refcursor;
7 begin
8 select sum(val1), sum(val2), sum(val3)
9 into l_sum1 , l_sum2 , l_sum3
10 from test;
11
12 if l_sum1 is null and l_sum2 is null and l_sum3 is null then
13 open rc for select null from dual;
14 elsif l_sum1 is null and l_sum2 is null then
15 open rc for select l_sum3 from dual;
16 elsif l_sum1 is null and l_sum3 is null then
17 open rc for select l_sum2 from dual;
18 elsif l_sum2 is null and l_sum3 is null then
19 open rc for select l_sum1 from dual;
20 elsif l_sum1 is null then
21 open rc for select l_sum2, l_sum3 from dual;
22 elsif l_sum2 is null then
23 open rc for select l_sum1, l_sum3 from dual;
24 elsif l_sum3 is null then
25 open rc for select l_sum1, l_sum2 from dual;
26 end if;
27 return rc;
28 end;
29 /
Function created.
SQL>
Testing:
SQL> select f_test from dual;
F_TEST
--------------------
CURSOR STATEMENT : 1
CURSOR STATEMENT : 1
:B2 :B1
---------- ----------
3 9
SQL> update test set val3 = null;
3 rows updated.
SQL> select f_test from dual;
F_TEST
--------------------
CURSOR STATEMENT : 1
CURSOR STATEMENT : 1
:B1
----------
3
In a more complex situation, with more columns, such an approach would be close to suicide so you'd have to do that differently, use dynamic SQL which makes things not that easy, so the question is: is it worth it? I don't think so.

How use SYS_REFCURSUR in select for update in pl/sql

I want to select multiple rows and also update all selected rows. so this goal i wrote this query. but when execute it throw exception.
I wrote this query in a producer like bellow.
PROCEDURE get_rows(
a_cursor OUT SYS_REFCURSOR,
a_id IN VARCHAR,
a_count IN NUMBER);
exception detail:
java.sql.SQLException: ORA-01002: fetch out of sequence
a_cursor is SYS_REFCURSOR
OPEN a_cursor FOR
SELECT mytable.VID
FROM mytable
WHERE ROWNUM <= COUNT FOR UPDATE;
loop
FETCH a_cursor INTO a_id;
if a_cursor %notfound then
cnumber := 9999;
else
UPDATE mytable SET
...
WHERE VID = a_vid;
COMMIT;
end if;
end loop;
A sys_refcursor cannot be used in update statement. You can use an explicit cursor as shown below. Use this way:
DECLARE
cursor a_cursor is
SELECT mytable.VID
FROM mytable
WHERE ROWNUM <= COUNT FOR UPDATE;
a_id number;
begin
OPEN a_cursor;
loop
FETCH a_cursor INTO a_id;
exit when a_cursor%notfound;
UPDATE mytable SET
...
WHERE VID = a_vid;
end loop;
COMMIT;
close a_cursor;
end;
Edit:
create or replace PROCEDURE get_rows(
a_cursor OUT SYS_REFCURSOR,
a_id IN VARCHAR,
a_count IN NUMBER)
IS
cursor a_cur is
SELECT mytable.VID
FROM mytable
WHERE ROWNUM <= a_COUNT ;
a_id NUMBER;
cnumber number;
BEGIN
OPEN a_cur;
LOOP
FETCH a_cur INTO a_id;
IF a_cur%notfound THEN
cnumber := 9999;
End if;
exit when a_cursor%notfound;
UPDATE mytable SET
...
WHERE VID = a_vid;
END loop;
COMMIT;
CLOSE a_cur;
Open a_cursor for select * from mytable;
end ;
If you are not doing any other processing in the loop, you can use a MERGE statement instead of a cursor:
SQL Fiddle
Oracle 11g R2 Schema Setup:
CREATE TABLE mytable ( vid, columna ) AS
SELECT 1, 'a' FROM DUAL UNION ALL
SELECT 2, 'a' FROM DUAL UNION ALL
SELECT 3, 'a' FROM DUAL UNION ALL
SELECT 4, 'a' FROM DUAL UNION ALL
SELECT 5, 'a' FROM DUAL UNION ALL
SELECT 6, 'a' FROM DUAL;
Query 1:
MERGE INTO mytable dst
USING (
SELECT VID /* or ROWID AS rid */
FROM mytable
WHERE ROWNUM <= 3
) src
ON ( src.VID = dst.VID /* or src.RID = dst.ROWID */ )
WHEN MATCHED THEN
UPDATE SET
columna = 'b'
Query 2:
SELECT * FROM mytable
Results:
| VID | COLUMNA |
|-----|---------|
| 1 | b |
| 2 | b |
| 3 | b |
| 4 | a |
| 5 | a |
| 6 | a |

Split multi column semicolon separated string and create records

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;