Spool the data from execute immediate within pl/sql block - oracle

Ho to spool the data from execute immediate in pl/sql.
Below is the code.
DECLARE
from_dt varchar(300):=&from_date;
to_dt varchar2(300):=&to_date;
account varchar2(200):=&account;
mbl_table varchar2(100);
dn_table varchar2(100);
id number;
Begin
select aid into id from account where upper(acode)=upper(account);
select tablename into mbl_table from partner_mbl where pid in (select pid from account where upper(acode)=upper(account));
select dn_tablename into dn_table from partner_mbl where pid in (select pid from account where upper(acode)=upper(account));
dbms_output.put_line(mbl_table);
FOR i IN (select 'p_'||to_char((ROWNUM-1 + to_date(from_dt, 'ddmonyyyy')),'ddmonyyyy') part FROM all_objects
WHERE ROWNUM-2 < to_date(to_dt, 'ddmonyyyy')-to_date(from_dt, 'ddmonyyyy'))loop
execute immediate 'Select a.pcode,A.Acode,To_Char(A.Mobile),a.msg,a.senderid,To_Char(A.Rts,'||'''dd/mm/yyyy hh24:mi:ss'''||'),To_Char(A.Sts,'||'''dd/mm/yyyy hh24:mi:ss'''||'),A.Statusflag,A.Statusid,To_Char(B.Lastts,'||'''dd/mm/yyyy hh24:mi:ss'''||'),B.Statusflag,B.Err_Des From '|| mbl_table ||' partition('||i.part||') A, '|| dn_table ||' partition('||i.part||') B Where a.aid='||id|| ' And A.Msgid = B.Msgid(+)';
end loop;
End;
how to spool the output of execute immediate into csv file

DECLARE
from_dt varchar(300) := &from_date;
to_dt varchar2(300) := &to_date;
account varchar2(200) := &account;
mbl_table varchar2(100);
dn_table varchar2(100);
id number;
/*define types*/
/* change the next varchar2(1000) with your types*/
t_pcode IS TABLE OF varchar2(1000);
v_pcode t_pcode;
t_Acode IS TABLE OF varchar2(1000);
v_Acode t_Acode;
t_Mobile IS TABLE OF varchar2(1000);
v_Mobile t_Mobile;
t_msg IS TABLE OF varchar2(1000);
v_msg t_msg;
t_senderid IS TABLE OF varchar2(1000);
v_senderid t_senderid;
t_Rts IS TABLE OF varchar2(1000);
v_Rts t_Rts;
t_Sts IS TABLE OF varchar2(1000);
V_Sts t_Sts;
t_Statusflag IS TABLE OF varchar2(1000);
v_Statusflag t_Statusflag;
t_Statusid IS TABLE OF varchar2(1000);
v_Statusid t_Statusid;
t_Lastts IS TABLE OF varchar2(1000);
v_Lastts t_Lastts;
t_Statusflag IS TABLE OF varchar2(1000);
v_Statusflag t_Statusflag;
t_Err_Des IS TABLE OF varchar2(1000);
v_Err_Des t_Err_Des;
/*end types*/
Begin
select aid into id from account where upper(acode) = upper(account);
select tablename
into mbl_table
from partner_mbl
where pid in
(select pid from account where upper(acode) = upper(account));
select dn_tablename
into dn_table
from partner_mbl
where pid in
(select pid from account where upper(acode) = upper(account));
dbms_output.put_line(mbl_table);
FOR i IN (select 'p_' ||
to_char((ROWNUM - 1 + to_date(from_dt, 'ddmonyyyy')),
'ddmonyyyy') part
FROM all_objects
WHERE ROWNUM - 2 < to_date(to_dt, 'ddmonyyyy') -
to_date(from_dt, 'ddmonyyyy')) loop
/* execute immediate 'Select a.pcode,A.Acode,To_Char(A.Mobile),a.msg,a.senderid,To_Char(A.Rts,' ||
'''dd/mm/yyyy hh24:mi:ss''' || '),To_Char(A.Sts,' ||
'''dd/mm/yyyy hh24:mi:ss''' ||
'),A.Statusflag,A.Statusid,To_Char(B.Lastts,' ||
'''dd/mm/yyyy hh24:mi:ss''' ||
'),B.Statusflag,B.Err_Des From ' || mbl_table ||
' partition(' || i.part || ') A, ' || dn_table ||
' partition(' || i.part || ') B Where a.aid=' || id ||
' And A.Msgid = B.Msgid(+)' ;
*/
execute immediate 'Select a.pcode,A.Acode,To_Char(A.Mobile),a.msg,a.senderid,To_Char(A.Rts,' ||
'''dd/mm/yyyy hh24:mi:ss''' || '),To_Char(A.Sts,' ||
'''dd/mm/yyyy hh24:mi:ss''' ||
'),A.Statusflag,A.Statusid,To_Char(B.Lastts,' ||
'''dd/mm/yyyy hh24:mi:ss''' ||
'),B.Statusflag,B.Err_Des From ' || mbl_table ||
' partition(' || i.part || ') A, ' || dn_table ||
' partition(' || i.part || ') B Where a.aid=' || id ||
' And A.Msgid = B.Msgid(+)'
BULK COLLECT INTO v_pcode, v_Acode, v_Mobile, v_msg, v_senderid,
v_Rts, V_Sts, v_Statusflag, v_Statusid, v_Lastts,
v_Statusflag, v_Err_Des;
for i.. v_pcode.count loop
dbms_output.put_line('pcode and msg values are: '||v_pcode(i)||' ' ||v_msg(i) ||' at line' || i );
/*you can get out other values with same way*/
end loop;
End;

you can also take a look at oracle documentation for "oracle collections", "execute immediate", "bulk collect".
my previous post could solve your problem however here is a simple example as additional info.
DECLARE
TYPE emp_typ IS TABLE OF scott.emp%ROWTYPE;
e_tab emp_typ;
BEGIN
EXECUTE IMMEDIATE 'SELECT * FROM emp'
BULK COLLECT INTO e_tab;
DBMS_OUTPUT.put_line('Dynamic EXECUTE: ' || e_tab.count);
for i in 1..e_tab.count loop
DBMS_OUTPUT.put_line( e_tab(i).ename ||':'|| e_tab(i).empno );
null;
end loop;
END;
/

Related

ORA-00936: missing expression - Line 62

I've been trying to identify what's wrong with the Insert Statement in the Execute Immediate for few hours without luck. Made sure that I am not missing any commas or entering any incorrect character.
I have gone through all the answers on SO and other websites trying to figure out what could I be doing wrong but no luck.
Running this function results in the following error (error line starts with "-->" Please ignore it as its just for highlighting purpose):
ORA-00936: missing expression
ORA-06512: at "BDW_AMPS.COUNT_RECORDS", line 62
and here's the PL/SQL Code for the function:
CREATE OR REPLACE FUNCTION count_records (
p_test_case_id IN NUMBER,
p_table_name IN VARCHAR2
) RETURN VARCHAR2 IS
v_amt_recs INT;
v_test_result VARCHAR2(10);
v_threshold_val VARCHAR2(10);
v_test_suite_table VARCHAR2(100);
v_test_result_id NUMBER;
v_batch_id NUMBER;
v_report_id NUMBER;
v_test_seq_no NUMBER;
v_session_name VARCHAR2(100);
v_error_description VARCHAR2(100);
v_process_by VARCHAR2(100);
BEGIN
v_test_suite_table := 'bdw_amps.spares_bdw_test_suite';
v_process_by := 'INFORMATICA';
EXECUTE IMMEDIATE 'SELECT THRESHHOLD_VALUE FROM '
|| v_test_suite_table
|| ' WHERE TEST_CASE_ID = '
|| p_test_case_id
INTO v_threshold_val;
EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ' || p_table_name
INTO v_amt_recs;
EXECUTE IMMEDIATE 'SELECT BDW_AMPS.SPARES_TEST_SEQ_ID_SEQ.NEXTVAL FROM DUAL'
INTO v_test_result_id;
EXECUTE IMMEDIATE 'SELECT MAX(BATCH_ID) FROM BDW_AMPS.spares_bdw_session_audit
WHERE SESSION_NAME=(SELECT SESSION_NAME FROM '
|| v_test_suite_table
|| ' WHERE TEST_CASE_ID = '
|| p_test_case_id
|| ')'
INTO v_batch_id;
EXECUTE IMMEDIATE 'SELECT REPORT_ID FROM '
|| v_test_suite_table
|| ' WHERE TEST_CASE_ID = '
|| p_test_case_id
INTO v_report_id;
EXECUTE IMMEDIATE 'SELECT TEST_SEQ FROM '
|| v_test_suite_table
|| ' WHERE TEST_CASE_ID = '
|| p_test_case_id
INTO v_test_seq_no;
EXECUTE IMMEDIATE 'SELECT SESSION_NAME FROM '
|| v_test_suite_table
|| ' WHERE TEST_CASE_ID = '
|| p_test_case_id
INTO v_session_name;
IF
v_amt_recs > v_threshold_val
THEN
v_test_result := 'PASS';
--> EXECUTE IMMEDIATE 'INSERT INTO BDW_AMPS.spares_bdw_test_results(
TEST_RESULT_ID,
BATCH_ID,
REPORT_ID,
TEST_CASE_ID,
TEST_SEQ_NO,
TABLE_NAME,
SESSION_NAME,
TEST_RESULT,
PROCESS_DATE,
PROCESS_BY
)
VALUES
('|| v_test_result_id || ',
' || v_batch_id || ',
' || v_report_id || ',
' || p_test_case_id || ',
' || v_test_seq_no || ',
' || p_table_name || ',
' || v_session_name || ',
' || v_test_result || ',
SYSDATE,
' || v_process_by || '
)';
EXECUTE IMMEDIATE 'commit';
ELSE
v_test_result := 'FAIL';
v_error_description := 'Count: ' || v_amt_recs || ' is greater than threshold value: ' || v_threshold_val;
EXECUTE IMMEDIATE 'INSERT INTO BDW_AMPS.spares_bdw_test_results(
TEST_RESULT_ID,
BATCH_ID,
REPORT_ID,
TEST_CASE_ID,
TEST_SEQ_NO,
TABLE_NAME,
SESSION_NAME,
TEST_RESULT,
ERROR_DESCRIPTION,
PROCESS_DATE,
PROCESS_BY
)
VALUES (
'|| v_test_result_id || ',
' || v_batch_id || ',
' || v_report_id || ',
' || p_test_case_id || ',
' || v_test_seq_no || ',
' || p_table_name || ',
' || v_session_name || ',
' || v_test_result || ',
' || v_error_description || ',
SYSDATE,
' || v_process_by || '
)';
EXECUTE IMMEDIATE 'commit';
END IF;
RETURN v_test_result;
END;
Assuming that this is a simplified example of something that really does need to be dynamic, one issue is that the string values are not quoted. (If you'd had date values they would need special handling too.)
For example:
create table demo (numcol number, stringcol varchar2(20));
declare
l_num number := 123;
l_string varchar2(20) := 'Kittens';
l_sql long := 'insert into demo(numcol, stringcol) values ('||l_num||', '||l_string||')';
begin
dbms_output.put_line(l_sql);
execute immediate l_sql;
end;
/
Generated code:
insert into demo(numcol, stringcol) values (123, Kittens)
Fails with:
ORA-00984: column not allowed here
The error will vary depending on the contents of the string. For example, if it contains spaces:
declare
l_num number := 123;
l_string varchar2(20) := 'Kittens are cute';
l_sql long := 'insert into demo(numcol, stringcol) values ('||l_num||', '||l_string||')';
begin
dbms_output.put_line(l_sql);
execute immediate l_sql;
end;
/
Generated code:
insert into demo(numcol, stringcol) values (123, Kittens are cute)
ORA-00917: missing comma
or commas:
declare
l_num number := 123;
l_string varchar2(20) := 'Kittens, Puppies';
l_sql long := 'insert into demo(numcol, stringcol) values ('||l_num||', '||l_string||')';
begin
dbms_output.put_line(l_sql);
execute immediate l_sql;
end;
/
insert into demo(numcol, stringcol) values (123, Kittens, Puppies)
ORA-00913: too many values
You need to build the quoting:
declare
l_num number := 123;
l_string varchar2(20) := 'Kittens, Puppies';
l_sql long := 'insert into demo(numcol, stringcol) values ('||l_num||', '''||l_string||''')';
begin
dbms_output.put_line(l_sql);
execute immediate l_sql;
end;
/
so that you generate
insert into demo(numcol, stringcol) values (123, 'Kittens, Puppies')
(If the string could contain quote characters, that would need more work.)
It's worth always building the dynamic SQL as a variable and printing or logging it on failure, as it's usually pretty clear what the issue is when you can see the code.
Another point is that concatenating values like this is resource-intensive, as Oracle tries to cache SQL statements for reuse, so they will be individually parsed and optimised and take space in the cache, but they will never be reused. If this is going to be frequently run with different values, you should consider using bind variables via the using clause of execute immediate.
Your DML(INSERT) statements do not need EXECUTE IMMEDIATE statements. So, remove them after line 61 :
CREATE OR REPLACE FUNCTION count_records (
p_test_case_id IN NUMBER,
p_table_name IN VARCHAR2
) RETURN VARCHAR2 IS
v_amt_recs INT;
v_test_result VARCHAR2(10);
v_threshold_val VARCHAR2(10);
v_test_suite_table VARCHAR2(100);
v_test_result_id NUMBER;
v_batch_id NUMBER;
v_report_id NUMBER;
v_test_seq_no NUMBER;
v_session_name VARCHAR2(100);
v_error_description VARCHAR2(100);
v_process_by VARCHAR2(100);
BEGIN
v_test_suite_table := 'bdw_amps.spares_bdw_test_suite';
v_process_by := 'INFORMATICA';
EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ' || p_table_name
INTO v_amt_recs;
v_test_result_id := BDW_AMPS.SPARES_TEST_SEQ_ID_SEQ.NEXTVAL;
EXECUTE IMMEDIATE 'SELECT MAX(BATCH_ID) FROM BDW_AMPS.spares_bdw_session_audit
WHERE SESSION_NAME=(SELECT SESSION_NAME FROM '
|| v_test_suite_table
|| ' WHERE TEST_CASE_ID = '
|| p_test_case_id
|| ')'
INTO v_batch_id;
EXECUTE IMMEDIATE 'SELECT THRESHHOLD_VALUE, REPORT_ID, TEST_SEQ,SESSION_NAME FROM '
|| v_test_suite_table
|| ' WHERE TEST_CASE_ID = :caseId'
INTO v_threshold_val,v_report_id,v_test_seq_no,v_session_name
USING p_test_case_id;
IF
v_amt_recs > v_threshold_val
THEN
v_test_result := 'PASS';
INSERT INTO BDW_AMPS.spares_bdw_test_results(
TEST_RESULT_ID,
BATCH_ID,
REPORT_ID,
TEST_CASE_ID,
TEST_SEQ_NO,
TABLE_NAME,
SESSION_NAME,
TEST_RESULT,
PROCESS_DATE,
PROCESS_BY
)
VALUES
( v_test_result_id ,
v_batch_id ,
v_report_id ,
p_test_case_id ,
v_test_seq_no ,
p_table_name ,
v_session_name ,
v_test_result ,
SYSDATE,
v_process_by
);
commit;
ELSE
v_test_result := 'FAIL';
v_error_description := 'Count: ' || v_amt_recs || ' is greater than threshold value: ' || v_threshold_val;
INSERT INTO BDW_AMPS.spares_bdw_test_results(
TEST_RESULT_ID,
BATCH_ID,
REPORT_ID,
TEST_CASE_ID,
TEST_SEQ_NO,
TABLE_NAME,
SESSION_NAME,
TEST_RESULT,
ERROR_DESCRIPTION,
PROCESS_DATE,
PROCESS_BY
)
VALUES (
v_test_result_id ,
v_batch_id ,
v_report_id ,
p_test_case_id ,
v_test_seq_no ,
p_table_name ,
v_session_name ,
v_test_result ,
v_error_description ,
SYSDATE,
v_process_by
);
commit;
END IF;
RETURN v_test_result;
END;
while usage of them are right for SELECT statements because of dynamic table names.

ORA-00904 invalid identifier error in dynamic SQL block

I'm running the below which once executed, an error is reported telling me that EST_ONE_ROW_MB is an invalid identifier.
I've been advised I perhaps need to get the dynamic SQL part running as a stand alone query to begin with as an initial troubleshooting exercise but I'm a bit stumped in terms of how to write a sub-query here that will produce the desired output and eliminate the error.
create or replace procedure JUST_ME is
--variables
l_dblink varchar2(100) := 'DB1';
file_handle UTL_FILE.file_type;
v_ts_name varchar2(30);
v_link_name varchar2(10);
v_csv_name varchar2(100);
EST_ONE_ROW_MB varchar2(100) ;
TOTAL_ROW_COUNT NUMBER;
SPACE_REQUIRED NUMBER;
TOT_OBJECT_SIZE_MB NUMBER;
v_Mv_name varchar2(100);
v_sql1 varchar2(1500);
cur SYS_REFCURSOR;
owner varchar2(100);
table_name varchar2(100);
driver_table varchar2(100);
mandatory_join varchar2(100);
C_TOTAL_ROW_COUNT varchar2(100);
v_total_driver_only varchar2(100);
--
begin
SELECT tablename into v_csv_name
FROM BOB01.BOB_new_table_tracker
WHERE
CREATED_AT = (select MAX(CREATED_AT) from BOB01.BOB_new_table_tracker);
SELECT mv_name into v_Mv_name
FROM BOB01.BOB_new_table_tracker_mv
WHERE
CREATED_AT = (select MAX(CREATED_AT) from BOB01.BOB_new_table_tracker_mv);
select link_name into v_link_name from link_and_mail where mdate = (select max(mdate) from link_and_mail);
select distinct targetschema into v_ts_name from BOB01.MV_BOB_TABLE;
v_sql1 := 'SELECT /*+ monitor parallel (4)*/ a.owner,
a.table_name,
b.driver_table,
b.mandatory_join,
sum(c.sum_bytes) TOT_OBJECT_SIZE_MB,
(TOT_OBJECT_SIZE_MB) / (:C_TOTAL_ROW_COUNT) AS "EST_ONE_ROW_MB",
(EST_ONE_ROW_MB) * (:TOTAL_ROW_COUNT) AS "SPACE_REQUIRED"
FROM dba_tables#DB1 a, '|| v_Mv_name ||' b, MV_PRD_SEG_DATA c
WHERE a.table_name IN ( SELECT table_name
FROM MV_BOB_TABLE
WHERE driver_table IS NOT NULL
AND additional_joins IS NULL
)
AND a.owner IN ( SELECT DISTINCT productionschema FROM MV_BOB_TABLE c )
and a.table_name = b.table_name
and a.table_name = c.segment_name
group by a.owner,a.table_name,b.driver_table,b.mandatory_join
ORDER BY table_name';
file_handle := utl_file.fopen('ESTIMATES_CSV', v_csv_name||'_EST_PROC.csv', 'w', 32767);
--
UTL_FILE.PUT_LINE(file_handle, ' ');
UTL_FILE.PUT_LINE(file_handle, 'The below report shows total row counts in PROD');
UTL_FILE.PUT_LINE(file_handle, ' for unjoined tables in the BOB document:');
UTL_FILE.PUT_LINE(file_handle, ' ');
utl_file.put_line(file_handle, 'OWNER,TABLE_NAME,MANDATORY_JOIN,TOT_OBJECT_SIZE_MB,EST_ONE_ROW_MB,TOTAL_ROW_COUNT,SPACE_REQUIRED');
--main loop
open cur for v_sql1 using TOTAL_ROW_COUNT,C_TOTAL_ROW_COUNT;
loop
fetch cur into OWNER,TABLE_NAME,MANDATORY_JOIN,TOT_OBJECT_SIZE_MB,EST_ONE_ROW_MB,TOTAL_ROW_COUNT,SPACE_REQUIRED;--,EST_ONE_ROW_MB;
exit when cur%NOTFOUND;
execute immediate' select /*+parallel (4)*/ count(*) from '||owner||'.'||table_name || '#' || l_dblink into TOTAL_ROW_COUNT;
execute immediate' select /*+monitor parallel (10)*/ count(*) from ' ||owner||'.'||table_name || '#' || l_dblink||' b '||','||
driver_table || '#' || l_dblink||' a ' ||' where ' ||mandatory_join into TOTAL_ROW_COUNT;
execute immediate' select /*+monitor parallel (10)*/ count(*) from ' ||owner||'.'||table_name || '#' || l_dblink into C_TOTAL_ROW_COUNT;
utl_file.put_line(file_handle,
OWNER || ',' ||
TABLE_NAME || ',' ||
TOT_OBJECT_SIZE_MB || ',' ||
TOTAL_ROW_COUNT || ',' ||
C_TOTAL_ROW_COUNT || ',' ||
round(TOT_OBJECT_SIZE_MB / C_TOTAL_ROW_COUNT,7)|| ',' ||
round(round(TOT_OBJECT_SIZE_MB / C_TOTAL_ROW_COUNT,7) * round(TOTAL_ROW_COUNT,0),0)
);
v_total_driver_only := v_total_driver_only + round(TOT_OBJECT_SIZE_MB / C_TOTAL_ROW_COUNT,7) * round(TOTAL_ROW_COUNT,0);
end loop;
UTL_FILE.PUT_LINE(file_handle, ' ');
utl_file.put_line(file_handle,
'Total Estimated Space Required '|| round(v_total_driver_only,0) ||' MB'
);
utl_file.fclose(file_handle);
end JUST_ME;
to use EST_ONE_ROW_MB on that way is not possible because its' not defied as column.
replace it by (TOT_OBJECT_SIZE_MB) / (:C_TOTAL_ROW_COUNT)
SELECT /*+ monitor parallel (4)*/ a.owner,
a.table_name,
b.driver_table,
b.mandatory_join,
sum(c.sum_bytes) TOT_OBJECT_SIZE_MB, -- will be the same problem
(sum(c.sum_bytes)) / (:C_TOTAL_ROW_COUNT) AS "EST_ONE_ROW_MB",
((sum(c.sum_bytes)) / (:C_TOTAL_ROW_COUNT)) * (:TOTAL_ROW_COUNT) AS "SPACE_REQUIRED"
...
you can do that if you have an Inline View. e.g.
select EST_ONE_ROW_MB * (:TOTAL_ROW_COUNT) AS "SPACE_REQUIRED"
from(
select (TOT_OBJECT_SIZE_MB) / (:C_TOTAL_ROW_COUNT) AS "EST_ONE_ROW_MB"
from ....
)

Oracle PLSQL invalid cursor error I don't understand

I'm still a relatively newbe when it comes to PL/SQL.
Using Oracle 12c on Linux RHEL 6.8, the following shell script will attempt to activate all RI constraints in a collection of tables, and if they fail with parent key failures, it will dump the first 100 rows (or less) of the offending data. Or at least that is the goal. Since the script deals mostly with system tables on 12c (with only a small user table list that is unique to my installation), I'm including the whole thing exactly from my environment.
The main work occurs in the exception handling where the system tables are queried for the constraint, and user queries are formed from those data.
As a extra goal, the output is rather messy and I want to clean it up, but first it has to work :)
The output / error I get for my tables is the following:
ERROR Handling here for table NRNG_MTC_VST Constraint Name:
SYS_C0011790 Final SQL = SELECT DISTINCT NRNG_MTC_VST.LOG_CRT_DT ,
NRNG_MTC_VST.NRRNG_MTC_LG_ID FROM ODB_PRIMARY.NRNG_MTC_VST WHERE NOT
EXISTS (SELECT 1 FROM ODB_PRIMARY.NRNG_MTC_LOG WHERE
NRNG_MTC_VST.LOG_CRT_DT = NRNG_MTC_LOG.LOG_CRT_DT AND
NRNG_MTC_VST.NRRNG_MTC_LG_ID = NRNG_MTC_LOG.NRRNG_MTC_LG_ID) FETCH
FIRST 100 rows only
---xxx End SQL DECLARE
* ERROR at line 1: ORA-01001: invalid cursor ORA-06512: at line 111 ORA-02298: cannot validate (ODB_PRIMARY.SYS_C0011790) - parent keys
not found
The output SQL from my print_line is correct, and would work if pasted directly into a SQLDeveloper session. There is just something silly about how the cursor is defined I don't understand.
The full text of the script. BYW, if you see other bonehead changes that should be made unrelated to the error, please suggest them as well.
cd $OGGHOME/scripts
export ORACLE_SID=odbod07 $ORACLE_HOME/bin/sqlplus <<-EOF / as sysdba
alter session set container=p01_odbod07;
set echo on set feedback on
set heading off
set serveroutput on size 10000
DECLARE finalsql varchar2(2048);
part1sql varchar2(1024) ;
part2sql varchar2(1024) := ' ';
cownername varchar2(1024);
ctablename varchar2(1024);
pownername varchar2(1024);
ptablename varchar2(1024);
cnt number := 0;
-- Weak cursor defs
my_cursor sys_refcursor;
BEGIN FOR i in (
select owner, table_name, constraint_name
from dba_constraints
where constraint_type = 'R'
and status = 'DISABLED'
and owner = 'ODB_PRIMARY'
and TABLE_NAME in
-- enter user tables with RI constraints here
('RRNG_MTC_STN_CPLY',
'NRNG_MTC_VST_MTRL_USG',
'NRNG_MTC_VST',
'CAR_CORE',
'NRNG_MTC_LOG'))
-- end user table definitions, rest of code should rely only on system tables
LOOP BEGIN
dbms_output.put_line('alter table '||i.owner|| '.' ||
i.table_name || ' enable constraint '||i.constraint_name);
execute immediate 'alter table '||i.owner|| '.' ||
i.table_name || ' enable constraint '||i.constraint_name;
EXCEPTION
-- exception handling - dump offending data
WHEN OTHERS THEN -- take all exceptions for now
dbms_output.put_line ('ERROR Handling here for table ' ||
i.table_name || ' Constraint Name: ' ||i.constraint_name);
finalsql := 'SELECT DISTINCT ';
part1sql := '';
part2sql := ' ';
cnt := 0;
for constraint in (
SELECT ucc1.OWNER as childowner,
ucc1.TABLE_NAME as childtable,
ucc1.column_name as childcolumn,
ucc2.OWNER as parentowner,
ucc2.TABLE_NAME as parenttable,
ucc2.column_name as parentcolumn,
utc1.data_type as childdatatype,
utc1.data_length as childdatalen
FROM all_constraints uc ,
all_cons_columns ucc1 ,
all_cons_columns ucc2,
all_tab_columns utc1
WHERE
uc.constraint_name = ucc1.constraint_name
AND uc.r_constraint_name = ucc2.constraint_name
AND ucc1.POSITION = ucc2.POSITION
AND ucc1.table_name = utc1.table_name
AND ucc1.column_name = utc1.column_name
AND uc.constraint_type = 'R'
AND uc.constraint_name = i.constraint_name
ORDER BY ucc1.TABLE_NAME , uc.constraint_name)
loop
cownername := constraint.childowner;
ctablename := constraint.childtable;
pownername := constraint.parentowner;
ptablename := constraint.parenttable;
if cnt > 0 then
part1sql := part1sql || ' , ';
part2sql := part2sql || ' AND ';
end if;
part1sql := part1sql || constraint.childtable ||
'.'||constraint.childcolumn || ' ';
part2sql := part2sql || constraint.childtable || '.'
|| constraint.childcolumn || ' = '
|| constraint.parenttable || '.' ||
constraint.parentcolumn;
cnt := cnt + 1;
end loop;
finalsql := finalsql || part1sql ||
' FROM ' || ' ' || cownername ||
'.' || ctablename ||
' WHERE NOT EXISTS (SELECT 1 FROM ' ||
pownername || '.' || ptablename ||
' WHERE ' || part2sql || ') FETCH FIRST 100 rows only';
dbms_output.put_line ('Final SQL = ' || finalsql);
dbms_output.put_line ('---xxx End SQL');
open my_cursor for finalsql;
dbms_sql.return_result(my_cursor);
close my_cursor;
-- EXECUTE IMMEDIATE finalsql;
END;
end loop; end;
/
EOF
Many thanks for any help provided.
Brian
Just to narrow this down to a simple test case, I think this is the error you are seeing:
declare
my_cursor sys_refcursor;
begin
open my_cursor for 'select ''Hello, world'' as message from dual';
dbms_sql.return_result(my_cursor);
close my_cursor; -- << Remove this line
end;
/
ERROR at line 1:
ORA-01001: invalid cursor
ORA-06512: at line 6
This is because you attempted to close the cursor when you have already passed it to dbms_sql for processing. Remove the line with close my_cursor.
declare
my_cursor sys_refcursor;
begin
open my_cursor for 'select ''Hello, world'' as message from dual';
dbms_sql.return_result(my_cursor);
end;
/
PL/SQL procedure successfully completed.
ResultSet #1
MESSAGE
------------
Hello, world
1 row selected.
I had same kind of issue when i tried to print Ref_cursor directly. Then i created a Record type variable and then fetched field values in that variable and then i used DBMS_OUTPUT for that record type variable.
Please see if below code and scenario can help you-
set serveroutput on;
declare
v_sql varchar2(1000);
v_cursor sys_refcursor;
type myrec is record(col1 varchar2(100),col2 varchar2(1000));
rec myrec;
begin
v_sql:='select name,status from t_employee where user_id in (''C001117'',''C001122'')';
open v_cursor for v_sql;
loop
fetch v_cursor
into rec;
exit when v_cursor%notfound;
dbms_output.put_line( rec.col1||':status '||rec.col2 );
end loop;
end;
/
The following is my semi-complete script. Given a table list, it will attempt to activate the RI Constraints, and if they fail it will print out the FK data records in the child table that prevent it from being applied.
The hardest part of this project was the fact that the FKs can be any number of columns and of any type, so the print the results of the select in this case was very tricky (IMO).
Thanks for the help people provided.
cd $OGGHOME/scripts
. ./functions.sh
$ORACLE_HOME/bin/sqlplus ${ORACLE_USERID}/${ORACLE_PASSWORD}#${ORACLE_SID} << EOF
set echo on
set feedback on
set heading off
set serveroutput on size unlimit
DECLARE
finalsql varchar2(2048);
part1sql varchar2(1024) ;
part2sql varchar2(1024) := ' ';
cownername varchar2(1024);
ctablename varchar2(1024);
pownername varchar2(1024);
ptablename varchar2(1024);
cnt number := 0;
desc_tab dbms_sql.desc_tab;
col_count INTEGER;
cursor_name INTEGER;
-- Weak cursor defs
my_cursor sys_refcursor;
col1 varchar2(50);
d number;
j number;
lineout varchar2(2048);
plineout varchar2(2048);
rows number;
eCount number := 0;
BEGIN
FOR i in (
select owner, table_name, constraint_name
from dba_constraints
where constraint_type = 'R'
and status = 'DISABLED'
and owner = '$DBSCHEMA'
and TABLE_NAME in (
'RRNG_MTC_STN_CPLY',
'NRNG_MTC_VST_MTRL_USG',
'NRNG_MTC_VST',
'MTC_TSK_HRHY'))
LOOP
BEGIN
dbms_output.put_line ('.');
dbms_output.put_line ('=====================================');
dbms_output.put('alter table '||i.owner|| '.' || i.table_name || ' enable constraint '||i.constraint_name);
execute immediate 'alter table '||i.owner|| '.' || i.table_name || ' enable constraint '||i.constraint_name;
dbms_output.put_line (' ... SUCCESS');
EXCEPTION -- exception handling - dump offending data
WHEN OTHERS THEN
eCount := eCount + 1;
dbms_output.put_line (' ... FAILED. Constraint Name: ' || i.constraint_name);
finalsql := 'SELECT DISTINCT ';
part1sql := '';
part2sql := ' ';
cnt := 0;
for constraint in (
SELECT ucc1.OWNER as childowner,
ucc1.TABLE_NAME as childtable,
ucc1.column_name as childcolumn,
ucc2.OWNER as parentowner,
ucc2.TABLE_NAME as parenttable,
ucc2.column_name as parentcolumn,
utc1.data_type as childdatatype,
utc1.data_length as childdatalen
FROM all_constraints uc ,
all_cons_columns ucc1 ,
all_cons_columns ucc2,
all_tab_columns utc1
WHERE
uc.constraint_name = ucc1.constraint_name
AND uc.r_constraint_name = ucc2.constraint_name
AND ucc1.POSITION = ucc2.POSITION
AND ucc1.table_name = utc1.table_name
AND ucc1.column_name = utc1.column_name
AND uc.constraint_type = 'R'
AND uc.constraint_name = i.constraint_name
ORDER BY ucc1.TABLE_NAME ,
uc.constraint_name)
loop
cownername := constraint.childowner;
ctablename := constraint.childtable;
pownername := constraint.parentowner;
ptablename := constraint.parenttable;
if cnt > 0 then
part1sql := part1sql || ' , ';
part2sql := part2sql || ' AND ';
end if;
part1sql := part1sql || constraint.childtable || '.' || constraint.childcolumn || ' ';
part2sql := part2sql || constraint.childtable || '.' || constraint.childcolumn || ' = '
|| constraint.parenttable || '.' || constraint.parentcolumn;
cnt := cnt + 1;
end loop;
finalsql := finalsql || part1sql || ' FROM ' || ' ' || cownername || '.' || ctablename || ' WHERE NOT EXISTS (SELECT 1 FROM ' ||
pownername || '.' || ptablename || ' WHERE ' || part2sql || ') FETCH FIRST 100 rows only';
dbms_output.put_line ('Final SQL = (' || finalsql || ')');
-- dbms_output.put_line ('---xxx End SQL');
lineout := 'Child Table: ' || ctablename || '(';
plineout := 'Parent Table: ' || ptablename;
cursor_name := dbms_sql.open_cursor;
dbms_sql.PARSE (cursor_name, finalsql, DBMS_SQL.NATIVE);
d := dbms_sql.execute (cursor_name);
dbms_sql.describe_columns (cursor_name, col_count, desc_tab);
for j in 1..col_count
LOOP
DBMS_SQL.DEFINE_COLUMN (cursor_name, j, col1, 30);
lineout := lineout || desc_tab(j).col_name || ' , ';
-- plineout := plineout || constraint.parentcolumn || ' ';
-- dbms_output.put_line ('Column 1: ' || j || ' is ' || desc_tab(j).col_name || ' type '
-- || desc_tab(j).col_type);
END LOOP j;
lineout := lineout || ')';
-- plineout := plineout || ')';
dbms_output.put_line (lineout);
dbms_output.put_line (plineout);
lineout := NULL;
for j in 1..col_count
LOOP
if j > 1 then
lineout := lineout || ' ';
end if;
lineout := lineout || desc_tab(j).col_name;
END LOOP;
dbms_output.put_line (lineout);
dbms_output.put_line ('----------------------------------------');
LOOP
rows := dbms_sql.fetch_rows (cursor_name);
EXIT WHEN rows = 0;
lineout := NULL;
for j in 1..col_count
LOOP
dbms_sql.column_value (cursor_name, j, col1);
if j > 1 then
lineout := ltrim(lineout || ' ' || col1);
else
lineout := col1;
END IF;
END LOOP;
dbms_output.put_line (lineout);
END LOOP;
dbms_sql.close_cursor (cursor_name);
END;
end loop;
end;
/
EOF
your FETCH FIRST 100 rows only would seem to be out of place.
This is part of the BULK COLLECT clause in a SELECT statement in PL/SQL; as far as I know, it is not part of a SQL statement you can pass into a cursor like this
This is resulting in the cursor statement being invalid

Gettig error PLS-00364

I'm trying to create a stored procedure where I'm passing select statement to for loop and i'm using dynamic table which is passing at runtime and getting below error:
LINE 23 PLS-00364: loop index variable 'I' use is invalid
LINE 19 PL/SQL: ORA-00942: table or view does not exist
CREATE OR REPLACE PROCEDURE CREATE_TEST(TBL_NM IN VARCHAR2)
IS
SRC_ID NUMBER(38);
SQL_Q VARCHAR2(250);
DEL_F VARCHAR2(250);
BEGIN
FOR I in (SELECT DEL_IND FROM TBL_NM)
LOOP
SRC_ID := SRC_FILE_ID_SEQ.NEXTVAL;
IF I.DEL_IND = 0
THEN
execute immediate 'INSERT INTO TEST_HIST ' || ' (a,b,c,d,e,DEL_IND) ' ||
' SELECT a,b,c,d,e, '|| 0 || ' || ' FROM ' || TBL_NM;
ELSIF I.DEL_IND = 1
THEN
execute immediate 'INSERT INTO JESTX_IGNR ' || ' (a,b,c,d,e,DEL_IND,SRC_ID_NO) ' ||
' SELECT a,b,c,d,e, '|| 2 ||' , '|| SRC_ID || ' FROM ' || TBL_NM;
END IF ;
END LOOP;
COMMIT;
END;
I call the procedure using:
EXEC CREATE_TEST('abc');
What you want is a REF CURSOR as you cannot use cursor for loop with dynamic sql.
I dont know the exact datatype for your column DEL_IND. Please declare accordingly.
Here is some more information on Oracle REF CURSORS.
Try below
CREATE OR REPLACE PROCEDURE CREATE_TEST(TBL_NM IN VARCHAR2)
IS
TYPE c1ref is REF CURSOR;
SRC_ID NUMBER(38);
SQL_Q VARCHAR2(250);
DEL_F VARCHAR2(250);
DEL_IND NUMBER(5);
BEGIN
vsql_text := 'select DEL_IND from ' || TBL_NM;
open c1ref for vsql_text;
LOOP
SRC_ID := SRC_FILE_ID_SEQ.NEXTVAL;
fetch c1ref into DEL_IND;
exit when c1ref%NOTFOUND;
IF (DEL_IND = 0)
THEN
execute immediate 'INSERT INTO TEST_HIST ' || ' (a,b,c,d,e,DEL_IND) ' ||
' SELECT a,b,c,d,e, '|| 0 || ' || FROM ' || TBL_NM;
ELSIF (DEL_IND = 1)
THEN
execute immediate 'INSERT INTO JESTX_IGNR ' || ' (a,b,c,d,e,DEL_IND) ' ||
' SELECT a,b,c,d,e, '|| 2 ||' , '|| SRC_ID || ' FROM ' || TBL_NM;
END IF ;
END LOOP;
CLOSE c1ref;
COMMIT;
END;

Iterating all columns to find and replace a character

I want to iterate through all columns to find and replace a specific character. here is my pl/sql block:
Declare
match_count Number:=0;
v_search_string VARCHAR2(4000) := '%ي%';
BEGIN
FOR t IN
(SELECT owner,
table_name,
column_name
FROM all_tab_columns
WHERE (SUBSTR(table_name,1,2)='PN'
OR (SUBSTR(table_name,1,2) ='CD'
AND owner ='PNET_USER' ))
AND (data_type ='VARCHAR2'
OR data_type ='CLOB')
)
LOOP
BEGIN
EXECUTE IMMEDIATE 'SELECT count(*) FROM '||t.owner || '.' || t.table_name|| ' WHERE '||t.column_name||' LIKE :1' INTO match_count USING v_search_string;
IF match_count > 0 THEN
dbms_output.put_line( t.owner || '.' || t.table_name ||' '||t.column_name||' '||match_count );
--EXECUTE IMMEDIATE 'UPDATE '||t.table_name||' SET '||t.column_name||'=replace()'
END IF;
END;
END LOOP;
It works fine and prints the name of columns that have the invalid characters. But I don't know how to replace the characters. How can i get the value of t.column_name , replace the invalid character and then update the t.table_name ?
Well it was almost fine (and stevo's answer also). I let you change v_from and v_to with your chars.
Declare
match_count Number :=0;
v_from varchar2(5) := 'a';
v_like varchar2(5) := '%'||v_from||'%';
v_to varchar2(5) := 'b';
v_sql varchar2(1000);
v_emesg varchar2(1000);
CURSOR s is
(SELECT owner, table_name, column_name
FROM all_tab_columns
where SUBSTR(table_name,1,2) IN ('PN', 'CD')
AND owner ='PNET_USER'
AND data_type IN('VARCHAR2', 'CLOB'););
begin
for t in s LOOP
begin
EXECUTE IMMEDIATE 'SELECT count(*) FROM '||t.owner || '.' || t.table_name|| ' WHERE '||t.column_name||' LIKE :1' INTO match_count USING v_like;
IF match_count > 0 THEN
begin
dbms_output.put_line( t.owner || '.' || t.table_name ||' '||t.column_name||' '||match_count );
v_sql := 'UPDATE '||t.owner||'.'||t.table_name||' SET '||t.column_name||'= REPLACE('||t.column_name||', '''||v_from||''', '''||v_to||''') WHERE '||t.column_name||' LIKE '''|| v_like||'''';
dbms_output.put_line(v_sql);
EXECUTE IMMEDIATE v_sql;
EXCEPTION WHEN OTHERS THEN
v_emesg := SQLERRM;
dbms_output.put_line(v_emesg);
dbms_output.put_line('Errow while trying to update '||t.owner||'.'||.t.table_name||' : column '||t.column_name||'.';
END;
END IF;
end;
END LOOP;
end;
Something like
EXECUTE IMMEDIATE 'UPDATE '||t.table_name||' SET '||t.column_name||'=replace('||t.column_name||',''FROM'',''TO'')'
Should do it, where FROM is the invalid character and TO is whatever you want to change it to.
See oracle docs in link for an explanation of how REPLACE works.
http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions134.htm.
NB I don't have anywhere to try this, so syntax might not be correct.

Resources