How to use an array in PL/SQL? - plsql

How do I make arrays in PL / SQL?
I have a string that I want to split on spaces and then loop through them all.

Declare your array like this:
"your array" apex_application_global.vc_arr2;
"your array" := APEX_UTIL.STRING_TO_TABLE("your string",' ');
FOR i IN 1.. "your array".COUNT LOOP
"Your string" := "Your string"|| "your array"(i);
END LOOP;
and there you have it

And this is the ultimate and universal solution without using any packages, just oracle SQL. See a full featured solution (including a pipelining function) over here: http://www.armbruster-it.org/index.php/12-it/pl-sql/20-string-tokenizer-with-oracle-pl-sql
declare
cursor c_tokenizer(ci_string in varchar2, ci_delimiter in varchar2) is
SELECT regexp_substr(str, '[^' || ci_delimiter || ']+', 1, LEVEL) AS splitted_element,
LEVEL AS element_no
FROM (SELECT rownum AS id, ci_string str FROM dual)
CONNECT BY instr(str, ci_delimiter, 1, LEVEL - 1) > 0
AND id = PRIOR id
AND PRIOR dbms_random.value IS NOT null;
l_string varchar2(100) := 'Hello World, I like PL/SQL';
l_delimiter varchar2(1) := ' ';
begin
-- extract each word of the string above (delimited by blank)
for c1 in c_tokenizer(l_string, l_delimiter) loop
dbms_output.put_line(c1.splitted_element);
end loop;
end;
The Result is:
Hello
World,
I
like
PL/SQL

Related

plsql Result consisted of more than one row. How to handel it

CREATE PROCEDURE book_check(book_Id varchar(64))
begin
declare book_available varchar(64);
select book_id into book_available
from book_copies
where No_of_Copies >0 and book_id=book_Id;
if(book_Id in book_available ) then
select concat ("Book available");
else
select concat ("Book not available");
end if;
end
//
what can i write in place of 'in' . I know the syntax i wrong .
It's easy - try something like this:
create or replace function book_check(book_id varchar) return varchar as
begin
for r in (select 1 from book_copies where no_of_copies > 0 and book_id = book_check.book_id) loop
return 'Book available';
end loop;
return 'Book not available';
end book_check;
/
It's unclear to me what you are trying to do. I assume you want to find out if a book is available or not and return that information to the caller of the function.
Your declaration of the procedure header and the variables is wrong.
Procedure or function parameters are not defined with a length for the datatype.
Inside a procedure or function you don't need declare
you can't have a select statement without putting the result somewhere. * Assigning a constant value to a variable is done using :=
If you want to return information to the caller, use a function, not a procedure
You should not give variables or parameters the same name as a column. A common naming convention in the Oracle world is to give parameters the prefix p_ and local variables the prefix l_ but anything that avoids a name clash between column names and variables is OK - just be consistent.
CREATE function book_check(p_book_id varchar)
return varchar
as
l_count integer;
l_result varchar(20);
begin
select count(*)
into l_count
from book_copies
where No_of_Copies > 0
and book_id = p_book_id;
if l_count > 0 then
l_result := 'Book available';
else
l_result := "Book not available";
end if;
return result;
end;
/
You should really take the time and read the PL/SQL Language reference. All the above is explained there.

Parsing string in PL/SQL and insert values into database with RESTful web service

I am reading the values which I want to insert into database. I am reading them by lines. One line is something like this:
String line = "6, Ljubljana, Slovenija, 28";
Web service needs to separate values by comma and insert them into database. In PL/SQL language. How do I do that?
Here is some pl/sql that I have used to parse through delimited strings and then extract the individual words. You may have to mess with it a bit when using with the web service but it works fine when you are running it right in oracle.
declare
string_line varchar2(4000);
str_cnt number;
parse_pos_1 number := 1;
parse_pos_2 number;
parsed_string varchar2(4000);
begin
--counting the number of commas in the string so we know how many times to loop
select regexp_count(string_line, ',') into str_cnt from dual;
for i in 1..str_cnt + 1
loop
--grabbing the position of the comma
select regexp_instr(string_line, ',', parse_pos_1) into parse_pos_2 from dual;
--grabbing the individual words based of the comma positions using substr function
--handling the last loop
if i = str_cnt + 1 then
select substr(string_line, parse_pos_1, length(string_line)+1 - parse_pos_1) into parsed_string from dual;
execute immediate 'insert into your_table_name (your_column_name) values (' || parsed_string || ' )';
execute immediate 'commit';
--handles the rest
else
select substr(string_line, parse_pos_1, parse_pos2 - parse_pos_1) into parsed_string from dual;
execute immediate 'insert into your_table_name (your_column_name) values (' || parsed_string || ' )';
execute immediate 'commit';
end if;
parse_pos_1 := parse_pos_2+1;
end loop;
end;
I found an answer to that particular question. If you have similar values to those I posted for a question, like numbers, which look something like this:
String line = "145, 899";
This string is sent via POST request (RESTful web service, APEX). Now getting the values in PL/SQL and inserting them into table looks something like this:
DECLARE
val1 NUMBER;
val2 NUMBER;
str CLOB;
BEGIN
str := string_fnc.blob_to_clob(:body); // we have to convert body
val1 := TO_NUMBER(REGEXP_SUBSTR(str, '[^,]+', 1, 1));
val2 := TO_NUMBER(REGEXP_SUBSTR(str, '[^,]+', 1, 2));
// REGEXP_SUBSTR(source, pattern, start_position, nth_appearance)
INSERT INTO PRIMER VALUES (val1, val2);
END;
However, this is the method to insert line by line into database, so if you have large amount of rows in a file to insert, this isn't a way to do it. But here is the example which I requested. I hope it helps to someone.

How to use a comma-separated list of strings as pl/sql stored function parameter inside a "NOT IN" clause of a select statement

I have a list of comma-separated strings (from a user input) and I'd like to use this list as a parameter in a pl/sql stored function in a nested sql block using a "not in where clause".
I can't find an elegant way to make it work...
That's what I'm thinking of:
CREATE TABLE example ( somevalue VARCHAR(36) NOT NULL);
--
INSERT INTO example VALUES ('value1');
INSERT INTO example VALUES ('value2');
INSERT INTO example VALUES ('value3');
--
SELECT * FROM example;
--
CREATE OR REPLACE
FUNCTION resultmaker(
ignoreList IN VARCHAR2)
RETURN VARCHAR2
IS
result VARCHAR2(4000);
BEGIN
result := 'Here is my calculated result, using ignorelist=' || ignoreList || ':' || CHR(10);
FOR rec IN
(SELECT DISTINCT somevalue
FROM example
WHERE somevalue NOT IN resultmaker.ignoreList -- here's my issue, the NOT IN clause using the parameter value
)
LOOP
result := result || 'not in ignorelist: ' || rec.somevalue || CHR(10);
END LOOP;
result := result || '.' || CHR(10);
--
RETURN result;
END resultmaker;
/
--
-- simulate function call with user input 'value2, value3'
SELECT resultmaker('value2, value3') FROM dual; -- doesn't work
--
DROP TABLE example;
DROP FUNCTION resultmaker;
Just pass the parameter like '"value2","value3"' and have your statement replace the double quote with single quotes like REPLACE(#Param1,'"','''').
Call to function: SELECT * FROM Function1('"value2","value3"')
Inside function: NOT IN REPLACE(#Param1,'"','''')
In every case you should parse that input. As there is no built-in string tokenizer in PL/SQL (at least I couldn't find it) You may want to look into these options,
http://blog.tanelpoder.com/2007/06/20/my-version-of-sql-string-to-table-tokenizer/
Does PL/SQL have an equivalent StringTokenizer to Java's?
After you parsed the string, you may create a new string like:
not_in_statement varchar2(1000);
CURSOR c1 IS select token from tokenized_strings_table;
BEGIN
not_in_statement := '('
FOR rec IN c1 LOOP
not_in_statement := not_in_statement || '''||rec.token||'''||','
END LOOP
not_in_statement := not_in_statement||')'
END
SELECT DISTINCT somevalue
FROM example
WHERE somevalue NOT IN not_in_statement
You may need to make it dynamic SQL, I did not have time to try.
Here's my solution using dynamic sql for my original question above:
CREATE TABLE example ( somevalue VARCHAR(36) NOT NULL);
--
INSERT INTO example VALUES ('value1');
INSERT INTO example VALUES ('value2');
INSERT INTO example VALUES ('value3');
--
SELECT * FROM example;
--
CREATE OR REPLACE
FUNCTION resultmaker(
ignoreList IN VARCHAR2)
RETURN VARCHAR2
IS
result VARCHAR2(4000);
example_cursor sys_refcursor;
rec example.somevalue%type;
BEGIN
result := 'Here is my calculated result, using ignorelist=' || ignoreList || ':' || CHR(10);
OPEN example_cursor FOR ( 'SELECT DISTINCT somevalue FROM example WHERE somevalue NOT IN (' || ignoreList || ')' );
FETCH example_cursor INTO rec;
WHILE example_cursor%found
LOOP
result := result || 'not in ignorelist: ' || rec || CHR(10);
FETCH example_cursor INTO rec;
END LOOP;
CLOSE example_cursor;
result := result || '.' || CHR(10);
--
RETURN result;
END resultmaker;
/
--
-- simulate function call with user input 'value2', 'value3'
SELECT resultmaker('''value2'', ''value3''') FROM dual;
--
DROP TABLE example;
DROP FUNCTION resultmaker;
The classic and probably correct solution would be to use PL/SQL table passing it as prameter...
There are some good solutions at asktom.oracle.com regarding taking a string of values and dynamically creating an IN clause for them:
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:210612357425

Can I pass an explicit cursor to a function/procedure for use in FOR loop?

I have a procedure that performs some calculations on all records returned by a cursor. It looks a bit like this:
PROCEDURE do_calc(id table.id_column%TYPE)
IS
CURSOR c IS
SELECT col1, col2, col3
FROM table
WHERE ...;
BEGIN
FOR r IN c LOOP
-- do some complicated calculations using r.col1, r.col2, r.col3 etc.
END LOOP;
END;
Now I have the case where I need to perform the exact same calculation on a different set of records that come from a different table. However, these have the same "shape" as in the above in example.
Is it possible to write a procedure that looks like this:
PROCEDURE do_calc2(c some_cursor_type)
IS
BEGIN
FOR r IN c LOOP
-- do the calc, knowing we have r.col1, r.col2, r.col3, etc.
END LOOP;
END;
I know about SYS_REFCURSOR, but I was wondering if it was possible to use the much more convenient FOR ... LOOP syntax and implicit record type.
Create a package.
Declare your cursor as package variable.
Use %rowtype to set function parameter type.
create or replace package test is
cursor c is select 1 as one, 2 as two from dual;
procedure test1;
function test2(test_record c%ROWTYPE) return number;
end test;
create or replace package body test is
procedure test1 is
begin
for r in c loop
dbms_output.put_line(test2(r));
end loop;
end;
function test2(test_record c%ROWTYPE) return number is
l_summ number;
begin
l_summ := test_record.one + test_record.two;
return l_summ;
end;
end test;
I had a similar problem, where I had two cursors that needed to be processed the same way, so this is how I figured it out.
DECLARE
--Define our own rowType
TYPE employeeRowType IS RECORD (
f_name VARCHAR2(30),
l_name VARCHAR2(30));
--Define our ref cursor type
--If we didn't need our own rowType, we could have this: RETURN employees%ROWTYPE
TYPE empcurtyp IS REF CURSOR RETURN employeeRowType;
--Processes the cursors
PROCEDURE process_emp_cv (emp_cv IN empcurtyp) IS
person employeeRowType;
BEGIN
LOOP
FETCH emp_cv INTO person;
EXIT WHEN emp_cv%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Name = ' || person.f_name ||
' ' || person.l_name);
END LOOP;
END;
--Defines the cursors
PROCEDURE mainProcedure IS
emp empcurtyp;
BEGIN
OPEN emp FOR SELECT first_name, last_name FROM employees WHERE salary > 50000;
process_emp_cv(emp);
CLOSE emp;
OPEN emp FOR SELECT first_name, last_name FROM kuren WHERE first_name LIKE 'J%';
process_emp_cv(emp);
CLOSE emp;
END;
BEGIN
mainProcedure;
END;
/
You can also use this if you want to bulk collect your cursors. You just need to change your helper procedure process_emp_cv; the rest can stay the same.
Using BULK COLLECT
--Processes the cursors
PROCEDURE process_emp_cv (emp_cv IN empcurtyp) IS
TYPE t_employeeRowTable IS TABLE OF employeeRowType;
employeeTable t_employeeRowTable;
BEGIN
LOOP
FETCH emp_cv BULK COLLECT INTO employeeTable LIMIT 50;
FOR indx IN 1 .. employeeTable.Count
LOOP
DBMS_OUTPUT.PUT_LINE('Name = ' || employeeTable(indx).f_name ||
' ' || employeeTable(indx).l_name);
END LOOP;
EXIT WHEN emp_cv%NOTFOUND;
END LOOP;
END;
Try this one, Usong ref cursor.
declare
type c is ref cursor;
c2 c;
type rec is record(
id number,
name varchar(20)
);
r rec;
procedure p1(c1 in out c,r1 in out rec)is begin
loop
fetch c1 into r1;
exit when c1%notfound;
dbms_output.put_line(r1.id || ' ' ||r1.name);
end loop;
end;
begin
open c2 for select id, name from student;
p1(c2,r);
end;
Yes you can use Cursor explicitly into procedure and function,for that cursor need to declare into package as variable

How to insert into a table correctly using table of records and forall in pl/sql

I want to insert records into MY_TABLE using forall. But the no. of records dat gets inserted keeps on changing with each test run! I think it has something to do with loop counter but I am not able to figure out. Here's the code snippet.
DECLARE
TYPE l_rec_type IS RECORD (
datakey SOURCE_TABLE.datakey%TYPE,
sourcekey SOURCE_TABLE.sourcekey%TYPE,
DESCRIPTION SOURCE_TABLE.DESCRIPTION%TYPE,
dimension_name SOURCE_TABLE.dimension_name%TYPE ,
data_type SOURCE_TABLE.data_type%TYPE
);
TYPE l_table_type IS TABLE OF l_rec_typeINDEX BY PLS_INTEGER;
l_table l_table_type;
l_cntr NUMBER;
BEGIN
FOR rec_dimname IN (SELECT dimension_name FROM dimension_table) LOOP
l_cntr1 := 1
FOR rec_source IN (SELECT * FROM source_table WHERE data_type IS NOT NULL) LOOP
l_table(l_ctr1).datakey := rec_source.datakey;
l_table(l_ctr1).sourcekey := rec_source.sourcekey;
l_table(l_ctr1).DESCRIPTION := rec_source.DESCRIPTION;
l_table(l_ctr1).dimension_name := rec_source.dimension_name;
l_table(l_ctr1).data_type := rec_source.data_type;
l_cntr1 := l_cntr1+1;
END LOOP
FORALL j IN l_table.FIRST..l_table.LAST
INSERT INTO my_table VALUES(l_table(j).datakey,
l_table(j).sourcekey,
l_table(j).DESCRIPTION,
l_table(j).dimension_name,
l_table(j).data_type,
1,
SYSDATE,
login_id
);
END LOOP;
END;
What am I doing wrong? Normal insert using for loop is inserting 5000 records. Another problem that I am facing is how to handle WHEN DUP_VAL_ON_INDEX and WHEN OTHERS exception using forall. In nornal for loop its easy. But I have to use FORALL for fast inserts. Please help!
Looking at your code I can see that you not delete the data stored in the pl/table inside your loop and you don't have a order by to your query's. So if the first iteration have more data then the second you will have duplicate data.
So after initializing your l_cntr1 var (l_cntr1 := 1) you must clear your pl/table:
l_table.delete;
Hope that helps.
Here's the fixed code. Plus SAVE EXCEPTIONS really saved my day!. Here is how I implemented the solution. Thank you all for your valuable time and suggestions.
DECLARE
TYPE l_rec_type IS RECORD (
datakey SOURCE_TABLE.datakey%TYPE,
sourcekey SOURCE_TABLE.sourcekey%TYPE,
DESCRIPTION SOURCE_TABLE.DESCRIPTION%TYPE,
dimension_name SOURCE_TABLE.dimension_name%TYPE ,
data_type SOURCE_TABLE.data_type%TYPE
);
TYPE l_table_type IS TABLE OF l_rec_typeINDEX BY PLS_INTEGER;
l_table l_table_type;
l_cntr NUMBER;
ex_dml_errors EXCEPTION;
PRAGMA EXCEPTION_INIT(ex_dml_errors, -24381);
login_id NUMBER := -1;
errm VARCHAR2(512);
err_indx NUMBER
BEGIN
FOR rec_dimname IN (SELECT dimension_name FROM dimension_table) LOOP
l_cntr1 := 1;
l_table.DELETE; -- Added
FOR rec_source IN (SELECT * FROM source_table WHERE data_type IS NOT NULL) LOOP
l_table(l_ctr1).datakey := rec_source.datakey;
l_table(l_ctr1).sourcekey := rec_source.sourcekey;
l_table(l_ctr1).DESCRIPTION := rec_source.DESCRIPTION;
l_table(l_ctr1).dimension_name := rec_source.dimension_name;
l_table(l_ctr1).data_type := rec_source.data_type;
l_cntr1 := l_cntr1+1;
END LOOP
FORALL j IN l_table.FIRST..l_table.LAST SAVE EXCEPTIONS
INSERT INTO my_table VALUES(l_table(j).datakey,
l_table(j).sourcekey,
l_table(j).DESCRIPTION,
l_table(j).dimension_name,
l_table(j).data_type,
1,
SYSDATE,
login_id
);
END LOOP;
END LOOP;
EXCEPTION
WHEN ex_dml_errors THEN
l_error_count := SQL%BULK_EXCEPTIONS.count;
DBMS_OUTPUT.put_line('Number of failures: ' || l_error_count);
errm := SQLERRM(-SQL%BULK_EXCEPTIONS(i).ERROR_CODE);
err_indx := SQL%BULK_EXCEPTIONS(i).error_index
FOR i IN 1 .. l_error_count LOOP
DBMS_OUTPUT.put_line('Error: ' || i ||
' Array Index: ' || SQL%BULK_EXCEPTIONS(i).error_index ||
' Message: ' || SQLERRM(-SQL%BULK_EXCEPTIONS(i).ERROR_CODE));
IF errm LIKE '%unique%constraint%violated' THEN -- Insert into my_multiple_entries_tbl on duplicate value on index DATAKEY
INSERT INTO my_multiple_entries_tbl(my_multiple_entries_tbl_seq.NEXTVAL,
l_table(err_indx).datakey,
l_table(err_indx).sourcekey,
l_table(err_indx).data_type,
SYSDATE,
login_id );
ELSE -- Insert into my_other_errors_tbl on other errors
INSERT INTO my_other_errors_tbl ( my_other_errors_tbl_seq.NEXTVAL,
l_table(err_indx).datakey,
l_table(err_indx).sourcekey,
l_table(err_indx).data_type,
SYSDATE,
login_id );
END IF;
END;
Your seem to be inserting exactly the same thing multiple times - you're solely looping through the count of dimension_table, which means it can be simplified to the following, which will be faster. At the bottom is a forall version.
You can't use exception when dup_val_on_index with either version, you have to do it row by row. Judging solely by what you've posted I suspect that you can actually achieve what you're trying to do in a single query and save all this problem completely ( including dealing with duplicate values ).
declare
i integer;
begin
select count(*)
into i
from dimension_table;
for j in 1 .. i loop
insert into my_table (datakey, sourcekey, description
, dimension_name, someother_column
, some_date_column, login_id
select datakey, sourcekey, description, dimension_name
, data_type, 1, sysdate, login_id -- previously missing
from source_table
where data_type is not null;
end loop;
commit;
end;
/
If, however, you really want to use forall you can do something like this:
declare
cursor c_src is
select datakey, sourcekey, description, dimension_name
, data_type, 1, sysdate, login_id -- previously missing
from source_table
where data_type is not null;
type t__src is table of c_src%rowtype index by binary_integer;
t_src t__src;
i integer;
begin
select count(*)
into i
from dimension_table;
for j in 1 .. i loop
open c_src;
loop
fetch c_src bulk collect into t_src;
forall k in t_src.first .. t_src.last
insert into my_table (datakey, sourcekey, description
, dimension_name, someother_column
, some_date_column, login_id
values t_src;
end loop;
close c_src;
end loop;
commit;
end;
/

Resources