How to update a clob column with data over 2 million characters - sql

I am trying to update a clob value with length > 2 million characters in PL/SQL. I am getting the error
String literal too long
Is there any way I can get around this error?
This is the PL/SQL code snippet I am trying to update the clob value with:
DECLARE
value clob;
clob_field clob;
fromindex integer;
offset integer;
chunks integer;
eclob clob;
sql_stmt clob;
BEGIN
fromindex := 1;
offset := 2;
clob_field := '<clob_value_with_length_2Million>';
chunks := 1+(dbms_lob.Getlength(clob_field) / 2);
value :='';
FOR chunk IN 1 .. chunks LOOP
IF ( chunk != 1) THEN
value := value || ' || ';
END IF;
value := value || 'to_clob('''||dbms_lob.Substr(clob_field, offset, fromindex)||''')';
fromindex := fromindex + 2;
END LOOP;
dbms_output.put_line(value);
sql_stmt := 'update mytable
set sources = ' || value ||' where scenario_id = 1 and entry_index = 1';
EXECUTE IMMEDIATE sql_stmt;
END;
I am getting the error at clob_field initialization and it is obvious as PL/SQl wont allow more than 32k characters. So, I am reaching out here to see if I can have any solution to my problem.

You can reduce the amount of code needed and improve performance of your code if you used bind variables. If you are attempting to build a different update statement each time, the database will need to come up with a execution plan for each different query. Using bind variables also removes the need of having to do any SQL sanitization to protect against SQL injection.
Example
SQL> CREATE TABLE mytable
2 AS
3 SELECT 1 AS scenario_id, 1 AS entry_index, EMPTY_CLOB () || 'clob1' AS sources FROM DUAL
4 UNION ALL
5 SELECT 2 AS scenario_id, 2 AS entry_index, EMPTY_CLOB () || 'clob2' AS sources FROM DUAL;
Table created.
SQL> SELECT * FROM mytable;
SCENARIO_ID ENTRY_INDEX SOURCES
----------- ----------- --------------------------------------------------------------------------------
1 1 clob1
2 2 clob2
SQL> DECLARE
2 clob_field CLOB;
3 l_scenario_id NUMBER;
4 l_entry_index NUMBER;
5 sql_stmt CLOB;
6 BEGIN
7 clob_field := '<clob_value_with_length_2Million>';
8 l_scenario_id := 1;
9 l_entry_index := 1;
10
11 sql_stmt :=
12 'update mytable set sources = :bind_clob where scenario_id = :scenario and entry_index = :entry';
13
14 EXECUTE IMMEDIATE sql_stmt
15 USING clob_field, l_scenario_id, l_entry_index;
16 END;
17 /
PL/SQL procedure successfully completed.
SQL> SELECT * FROM mytable;
SCENARIO_ID ENTRY_INDEX SOURCES
----------- ----------- --------------------------------------------------------------------------------
1 1 <clob_value_with_length_2Million>
2 2 clob2

Related

Find id then assign 1 if id found from table PL sql create procedure

I'm looking to create a procedure that looks for the given customer ID in the database. If the customer exists, it sets the variable found to 1. Otherwise, the found variable is set to 0. However, my call out code block does not provide a result. Did I miss something or my SELECT statement should be something else? Thank you.
CREATE OR REPLACE PROCEDURE find_customer(CUST_ID IN NUMBER, found OUT NUMBER) AS
CUSTID NUMBER := CUST_ID;
BEGIN
SELECT CUSTOMER_ID INTO CUSTID
FROM CUSTOMERS
WHERE CUSTOMER_ID = CUST_ID;
IF CUST_ID = NULL THEN
found := 1;
END IF;
EXCEPTION
WHEN no_data_found THEN
found := 0;
END;
/
DECLARE
CUSTOMER_ID NUMBER := 1;
found NUMBER;
BEGIN
find_customer(1,found);
DBMS_OUTPUT.PUT_LINE (found);
END;
I don't think there's anything other to it than the following part bellow. In your given example, it is not possible to get a null value from it as any null id would probably mean the item doesn't exist. Meaning it doesn't return a row, which triggers the NO_DATA_FOUND exception, which you catch.
This is what you wrote:
IF CUST_ID = NULL THEN
found := 1;
END IF;
This is probably what you meant:
IF CUST_ID IS NOT NULL THEN
found := 1;
END IF;
I'd rewrite it so that
you distinguish parameters from local variables from column names
use table aliases
fix what happens when something is found (is not null, line #11)
while testing, use variable you declared, not a constant (1)
So:
SQL> CREATE OR REPLACE PROCEDURE find_customer (par_cust_id IN NUMBER,
2 par_found OUT NUMBER)
3 AS
4 l_custid NUMBER;
5 BEGIN
6 SELECT c.customer_id
7 INTO l_custid
8 FROM customers c
9 WHERE c.customer_id = par_cust_id;
10
11 IF l_custid IS NOT NULL
12 THEN
13 par_found := 1;
14 END IF;
15 EXCEPTION
16 WHEN NO_DATA_FOUND
17 THEN
18 par_found := 0;
19 END;
20 /
Procedure created.
Testing:
SQL> SET SERVEROUTPUT ON
SQL> SELECT * FROM customers;
CUSTOMER_ID
-----------
100
SQL> DECLARE
2 l_customer_id NUMBER := 1;
3 l_found NUMBER;
4 BEGIN
5 find_customer (l_customer_id, l_found);
6 DBMS_OUTPUT.put_line (l_found);
7 END;
8 /
0
PL/SQL procedure successfully completed.
SQL> DECLARE
2 l_customer_id NUMBER := 100;
3 l_found NUMBER;
4 BEGIN
5 find_customer (l_customer_id, l_found);
6 DBMS_OUTPUT.put_line (l_found);
7 END;
8 /
1
PL/SQL procedure successfully completed.
SQL>
You can simplify it down to:
CREATE OR REPLACE PROCEDURE find_customer(
p_cust_id IN CUSTOMERS.CUSTOMER_ID%TYPE,
p_found OUT NUMBER
) AS
BEGIN
SELECT 1
INTO p_found
FROM CUSTOMERS
WHERE CUSTOMER_ID = p_cust_id;
EXCEPTION
WHEN no_data_found THEN
p_found := 0;
END;
/
The line CUSTOMER_ID = p_cust_id will not match if either side is NULL so you don't need any further checks.
Then you can call it using:
DECLARE
v_found NUMBER;
BEGIN
find_customer(1,v_found);
DBMS_OUTPUT.PUT_LINE (v_found);
END;
/
db<>fiddle here

EXECUTE IMMEDIATE DROP FUNCTION causes Oracle SQL Developer to hang

I have the following script. But whenever I include the line EXECUTE IMMEDIATE 'DROP FUNCTION table_exists';, SQL Developer seems to hang. Any idea what could be causing it?
If I cancel the task, the script runs to completion but doesn't drop the function. However, I can simply run DROP FUNCTION table_exists; in my DB connection and it drops the table no problem. Is it some quirk of PL/SQL?
CREATE OR REPLACE FUNCTION table_exists(table_name VARCHAR2)
RETURN BOOLEAN
AS
table_count NUMBER := 0;
exists_sql VARCHAR2(255);
BEGIN
exists_sql := 'SELECT COUNT(1) FROM tab WHERE tname = :tab_name';
EXECUTE IMMEDIATE exists_sql INTO table_count USING table_name;
RETURN table_count > 0;
END;
/
DECLARE
TYPE tables_array IS VARRAY(2) OF VARCHAR2(25); -- change varray size if running on dev
tables tables_array;
BEGIN
tables := tables_array(
'FOO',
'BAR'
);
FOR table_element IN 1 .. tables.COUNT LOOP
DBMS_OUTPUT.PUT_LINE('Backing up data for ' || tables(table_element));
IF table_exists(tables(table_element) || '_ORIGINAL') THEN
DBMS_OUTPUT.PUT_LINE(tables(table_element) || '_ORIGINAL already exists');
ELSE
EXECUTE IMMEDIATE 'CREATE TABLE ' || tables(table_element) || '_ORIGINAL AS SELECT * FROM '|| tables(table_element);
END IF;
END LOOP;
EXECUTE IMMEDIATE 'DROP FUNCTION table_exists';
COMMIT;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE ('Unexpected error: ' || sqlerrm);
ROLLBACK;
RAISE;
END;
/
Oracle won't drop a function which is being used in this very procedure.
Is there a workaround? Yes, at least one - submit a job which will do it in another session.
Sample tables (so that procedure won't fail because of that)
SQL> create table foo (id number);
Table created.
SQL> create table bar (id number);
Table created.
Create a function:
SQL> CREATE OR REPLACE FUNCTION table_exists(table_name VARCHAR2)
2 RETURN BOOLEAN
3 AS
4 table_count NUMBER := 0;
5 exists_sql VARCHAR2(255);
6 BEGIN
7 exists_sql := 'SELECT COUNT(1) FROM tab WHERE tname = :tab_name';
8 EXECUTE IMMEDIATE exists_sql INTO table_count USING table_name;
9
10 RETURN table_count > 0;
11 END;
12 /
Function created.
Is it here? Yes, it is:
SQL> desc table_Exists;
FUNCTION table_Exists RETURNS BOOLEAN
Argument Name Type In/Out Default?
------------------------------ ----------------------- ------ --------
TABLE_NAME VARCHAR2 IN
Run the main piece of code; note line #4 (declaration of a variable which will contain job number) and line #21 which submits a job.
SQL> DECLARE
2 TYPE tables_array IS VARRAY(2) OF VARCHAR2(25); -- change varray size if running on dev
3 tables tables_array;
4 i number; -- job number
5 BEGIN
6 tables := tables_array(
7 'FOO',
8 'BAR'
9 );
10
11 FOR table_element IN 1 .. tables.COUNT LOOP
12 DBMS_OUTPUT.PUT_LINE('Backing up data for ' || tables(table_element));
13 IF table_exists(tables(table_element) || '_ORIGINAL') THEN
14 DBMS_OUTPUT.PUT_LINE(tables(table_element) || '_ORIGINAL already exists');
15 ELSE
16 EXECUTE IMMEDIATE 'CREATE TABLE ' || tables(table_element) || '_ORIGINAL AS SELECT * FROM '|| tables(table_element);
17 END IF;
18 END LOOP;
19
20 -- EXECUTE IMMEDIATE 'DROP FUNCTION table_exists';
21 dbms_job.submit(i, 'begin execute immediate ''drop function table_exists''; end;');
22
23 COMMIT;
24
25 EXCEPTION
26 WHEN OTHERS THEN
27 DBMS_OUTPUT.PUT_LINE ('Unexpected error: ' || sqlerrm);
28 ROLLBACK;
29 RAISE;
30 END;
31 /
PL/SQL procedure successfully completed.
Is the function still here? Nope, it was dropped.
SQL> desc table_exists;
ERROR:
ORA-04043: object table_exists does not exist
SQL>

How to add an anonymous block with this code

A junior SQL developer was trying to write an anonymous block to but is running into issues. The code should count how many items a person can afford based on their budget. The are sure that the SQL works fine, and their logic for counting the number of products is OK, but they don’t remember the right syntax for creating an anonymous block. Help them by finding and fixing the three errors in the following PL/SQL:
BEGIN
DECLARE
firstName VARCHAR(50) := 'Rob';
budget NUMBER = 600;
counter NUMBER;
CURSOR all_products AS
SELECT product_name, list_price FROM oe.PRODUCT_information;
counter := 0;
FOR items IN all_products LOOP
IF (items.LIST_PRICE <= budget) THEN
counter := counter + 1;
END IF;
END LOOP;
DBMS_OUTPUT.PUT_LINE(firstName || ', you can afford ' || TO_CHAR(counter) || ' items.');
END;
Two minor mistakes:
DECLARE should go first, BEGIN-END next
you missed colon sign for the BUDGET variable
Test case:
SQL> set serveroutput on
SQL> create table product_information (product_name varchar2(20), list_price number);
Table created.
SQL> insert into product_Information values('Some product', 100);
1 row created.
Your code, fixed:
SQL> DECLARE
2 firstname VARCHAR(50):= 'Rob';
3 budget NUMBER := 600; -- missing colon
4 counter NUMBER;
5 cursor all_products is
6 SELECT product_name,
7 list_price
8 FROM product_information; -- I removed OE. (as I don't have that schema)
9
10 BEGIN
11 counter := 0;
12 FOR items IN all_products LOOP
13 IF(items.list_price <= budget)THEN
14 counter := counter + 1;
15 END IF;
16 END LOOP;
17
18 dbms_output.put_line(firstname
19 || ', you can afford '
20 || TO_CHAR(counter)
21 || ' items.');
22 END;
23 /
Rob, you can afford 1 items.
PL/SQL procedure successfully completed.
SQL>

How do you specify IN clause in a dynamic query using a variable?

In PL/SQL, you can specify the values for the IN operator using concatenation:
v_sql := 'select field1
from table1
where field2 in (' || v_list || ')';
Is it possible to do the same using a variable?
v_sql := 'select field1
from table1
where field2 in (:v_list)';
If so, how?
EDIT: With reference to Marcin's answer, how do I select from the resultant table?
declare
cursor c_get_csv_as_tables is
select in_list(food_list) food_list
from emp_food
where emp_type = 'PERM';
cursor c_get_food_list (v_food_table varchar2Table)is
select *
from v_food_table;
begin
for i in c_get_csv_as_tables loop
for j in c_get_food_list(i.food_list) loop
dbms_output.put_line(j.element);
end loop;
end loop;
end;
I get the following error:
ORA-06550: line 10, column 6:
PL/SQL: ORA-00942: table or view does not exist
ORA-06550: line 9, column 1:
PL/SQL: SQL Statement ignored
ORA-06550: line 15, column 34:
PLS-00364: loop index variable 'J' use is invalid
ORA-06550: line 15, column 13:
PL/SQL: Statement ignored
Like in #Sathya link, you can bind the varray (I took #Codo example):
CREATE OR REPLACE TYPE str_tab_type IS VARRAY(10) OF VARCHAR2(200);
/
DECLARE
l_str_tab str_tab_type;
l_count NUMBER;
v_sql varchar2(3000);
BEGIN
l_str_tab := str_tab_type();
l_str_tab.extend(2);
l_str_tab(1) := 'TABLE';
l_str_tab(2) := 'INDEX';
v_sql := 'SELECT COUNT(*) FROM all_objects WHERE object_type IN (SELECT COLUMN_VALUE FROM TABLE(:v_list))';
execute immediate v_sql into l_count using l_str_tab;
dbms_output.put_line(l_count);
END;
/
UPDATE: the first command can be replaced with:
CREATE OR REPLACE TYPE str_tab_type IS TABLE OF VARCHAR2(200);
/
then call:
l_str_tab.extend(1);
when ever you add a value
Unfortunately you cannot bind a list like this, however you can use a table function. Read this
Here's an example of usage based on your code:
declare
cursor c_get_csv_as_tables is
select in_list(food_list) food_list
from emp_food
where emp_type = 'PERM';
cursor c_get_food_list (v_food_table varchar2Table)is
select column_value food
from TABLE(v_food_table);
begin
for i in c_get_csv_as_tables loop
for j in c_get_food_list(i.food_list) loop
dbms_output.put_line(j.food);
end loop;
end loop;
end;
I used here a column_value pseudocolumn
Bind variable can be used in Oracle SQL query with "in" clause.
Works in 10g; I don't know about other versions.
Bind variable is varchar up to 4000 characters.
Example: Bind variable containing comma-separated list of values, e.g.
:bindvar = 1,2,3,4,5
select * from mytable
where myfield in
(
SELECT regexp_substr(:bindvar,'[^,]+', 1, level) items
FROM dual
CONNECT BY regexp_substr(:bindvar, '[^,]+', 1, level) is not null
);
As per #Marcin's answer you can't do this, however, there's a fair bit to add to that, as your query should actually work, i.e. run.
Simply put, you cannot use a bind variable for a table or column. Not only that, bind variables they are assumed to be a character, so if you want a number you have to use to_number(:b1) etc.
This is where your query falls down. As you're passing in a string Oracle assumes that your entire list is a single string. Thus you are effectively running:
select field1
from table1
where field2 = v_list
There is no reason why you can't do this a different way though. I'm going to assume you're dynamically creating v_list, which means that all you need to do is create this list differently. A series of or conditions is, purportedly :-), no different to using an in.
By purportedly, I mean never rely on something that's untested. Although Tom does say in the link that there may be performance constraints there's no guarantee that it wasn't quicker than using in to begin with. The best thing to do is to run the trace on your query and his and see what difference there is, if any.
SQL> set serveroutput on
SQL>
SQL> declare
2
3 l_string varchar2(32767);
4 l_count number;
5
6 begin
7
8 for xx in ( select rownum as rnum, a.*
9 from user_tables a
10 where rownum < 20 ) loop
11
12 if xx.rnum = 1 then
13 l_string := 'table_name = ''' || xx.table_name || '''';
14 else
15 l_string := l_string || ' or table_name = ''' || xx.table_name || '
''';
16 end if;
17
18 end loop;
19
20 execute immediate 'select count(*)
21 from user_tables
22 where ' || l_string
23 into l_count
24 ;
25
26 dbms_output.put_line('count is ' || l_count);
27
28 end;
29 /
count is 19
PL/SQL procedure successfully completed.

PLSQL - How to retrieve values into a collection given an array of values?

I have a procedure that accepts an array of folder IDs and needs to return a list of document IDs. Folders are associated to documents in a one-to-many relationship--there are many documents for each folder. Specifically, there is a documents table which has a parent_folderid fk to the folders table.
This is what I have:
PROCEDURE get_folder_documents_ (
paa_folderids_i IN gtyp_folderids_table
) IS
lnt_temp_docids &&MATTER_SCHEMA..docid_tab := &&MATTER_SCHEMA..docid_tab();
lv_current_table_size NUMBER := gnt_documentids.COUNT;
BEGIN
FOR i IN paa_folderids_i.FIRST .. paa_folderids_i.LAST
LOOP
SELECT documentid
BULK COLLECT INTO lnt_temp_docids
FROM t$documents
WHERE parent_folderid = paa_folderids_i(i);
FOR j IN 1 .. lnt_temp_docids.COUNT
LOOP
lv_current_table_size := lv_current_table_size + 1;
gnt_documentids.EXTEND(1);
gnt_documentids(lv_current_table_size) := lnt_temp_docids(j);
END LOOP;
END LOOP;
END get_folder_documents_;
Is there a better way?
If gtyp_folderids_table is declared as a SQL type (as opposed to a PL/SQL type) you could use it in a SQL statement via a table() function like this:
SELECT documentid
BULK COLLECT INTO gnt_documentids
FROM t$documents
WHERE parent_folderid in ( select * from table( paa_folderids_i));
edit
If you want a PL/SQL answer, in 10g there is a more effective way - or at least an approach which requires less typing ;).
Oracle introduced some neat-o set operators which we can use with collections. The following example uses MULTISET UNION to munge several collections into one...
SQL> set serveroutput on size unlimited
SQL>
SQL> declare
2 v1 sys.dbms_debug_vc2coll
3 := sys.dbms_debug_vc2coll('SAM I AM', 'FOX IN SOCKS');
4 v2 sys.dbms_debug_vc2coll
5 := sys.dbms_debug_vc2coll('MR KNOX', 'GRINCH');
6 v3 sys.dbms_debug_vc2coll
7 := sys.dbms_debug_vc2coll('LORAX', 'MAISIE');
8 v_all sys.dbms_debug_vc2coll := sys.dbms_debug_vc2coll();
9 begin
10 dbms_output.put_line('V_ALL has '|| v_all.count() ||' elements');
11 v_all := v1 multiset union v2;
12 dbms_output.put_line('V_ALL has '|| v_all.count() ||' elements');
13 v_all := v_all multiset union v3;
14 dbms_output.put_line('V_ALL has '|| v_all.count() ||' elements');
15 end;
16 /
V_ALL has 0 elements
V_ALL has 4 elements
V_ALL has 6 elements
PL/SQL procedure successfully completed.
SQL>
Find out more about collections in 10g.