PL/SQL function statement ignored error - oracle

i want to create funtion that truncate all user objects,
this is my script
CREATE OR REPLACE Function Truncate_user ( name_in IN varchar2 )
return number
is
cnumber number;
v_str1 varchar2(200) := null;
cursor get_sql is
select
'drop '||object_type||' '||owner||'. '|| object_name|| DECODE(OBJECT_TYPE,'TABLE',' CASCADE CONSTRAINTS PURGE') v_str1
from DBA_objects
where object_type in ('TABLE','VIEW','PACKAGE','TYPE','PROCEDURE','FUNCTION','TRIGGER','SEQUENCE','SYNONYM')
AND owner=name_in
order by object_type,object_name;
begin
open get_sql;
loop
fetch get_sql into v_str1;
if get_sql%notfound
then cnumber :=0;
end if;
execute immediate v_str1;
end loop;
RETURN 1;
close get_sql;
end;
/
after the execution i got these errors
Erreur(7,1): PL/SQL: SQL Statement ignored
Erreur(9,6): PL/SQL: ORA-00942: Table ou vue inexistante
but when i execute this code without make a function ,the operation is done!

Your user does not have the priviliges to access DBA_OBJECTS

Maybe there are objects that requires quoted identifiers (e.g. using lowercase letters), try
select 'drop '||object_type||' '||owner||'. "'|| object_name||'"'|| ...

Related

Oracle Function Select * from Query Not giving any Results

The following is the function definition I am using:
CREATE OR REPLACE FUNCTION MA_FACTSET.totalCustomers
RETURN number as
total INTEGER := 0;
FID VARCHAR2(30) := 'NT33H0-S-US';
stmt varchar2(1000);
BEGIN
execute immediate 'TRUNCATE TABLE MovingAverage';
execute immediate 'DROP TABLE MovingAverage';
execute immediate 'CREATE GLOBAL TEMPORARY TABLE MovingAverage
(ID INTEGER,
PDATE DATE,
PPRICE FLOAT,
MA1 FLOAT) ON COMMIT PRESERVE ROWS';
stmt := 'INSERT INTO MovingAverage (ID,PDATE,PPRICE) SELECT
ROWNUM,"DATE",P_PRICE FROM FP_BASIC_BD WHERE FS_PERM_SEC_ID = ''NT33H0-S-US''';
DBMS_OUTPUT.PUT_LINE(stmt);
execute immediate stmt;
dbms_output.put_line(SQL%ROWCOUNT);
commit;
execute immediate 'UPDATE MovingAverage A SET MA1 =(SELECT AVG(PPRICE)
FROM MovingAverage WHERE ID>=A.ID-5 AND ID<A.ID )' ;
dbms_output.put_line(SQL%ROWCOUNT);
commit;
execute immediate 'SELECT * FROM MovingAverage ORDER BY ID ASC';
dbms_output.put_line(SQL%ROWCOUNT);
commit;
dbms_output.put_line(total);
RETURN total;
END;
/
I have applied some checks to see whether the function is running properly or not, like getting SQL%ROWCOUNT.
The following is the DBMS output of the function:
INSERT INTO MovingAverage (ID,PDATE,PPRICE) SELECT ROWNUM,"DATE",P_PRICE FROM FP_BASIC_BD WHERE FS_PERM_SEC_ID = 'NT33H0-S-US'
4114
4114
0
0
I want know why rowcount of "SELECT * FROM MovingAverage ORDER BY ID ASC" is 0. And if there is any way to print complete table in Data Grid. I am using TOAD for Oracle.
I suggest you to rewrite your function removing dynamic sqls where not necessary. Also, If you have DDLs, DMLs don't use PL/SQL function, rather use procedure.
For select Statements in EXECUTE IMMEDIATE, it will work if you use BULK COLLECT INTO
CREATE OR REPLACE FUNCTION totalCustomers
RETURN NUMBER
AS
total INTEGER := 0;
FID VARCHAR2 (30) := 'NT33H0-S-US';
stmt VARCHAR2 (1000);
TYPE mrectype IS TABLE OF MovingAverage%ROWTYPE;
mrec mrectype;
BEGIN
EXECUTE IMMEDIATE 'TRUNCATE TABLE MovingAverage';
EXECUTE IMMEDIATE 'DROP TABLE MovingAverage';
EXECUTE IMMEDIATE 'CREATE GLOBAL TEMPORARY TABLE MovingAverage
(ID INTEGER,
PDATE DATE,
PPRICE FLOAT,
MA1 FLOAT) ON COMMIT PRESERVE ROWS';
stmt :=
'INSERT INTO MovingAverage (ID,PDATE,PPRICE) SELECT
ROWNUM,"DATE",P_PRICE FROM FP_BASIC_BD WHERE FS_PERM_SEC_ID = ''NT33H0-S-US''';
DBMS_OUTPUT.PUT_LINE (stmt);
EXECUTE IMMEDIATE stmt;
DBMS_OUTPUT.put_line (SQL%ROWCOUNT);
COMMIT;
EXECUTE IMMEDIATE 'UPDATE MovingAverage A SET MA1 =(SELECT AVG(PPRICE)
FROM MovingAverage WHERE ID>=A.ID-5 AND ID<A.ID )';
DBMS_OUTPUT.put_line (SQL%ROWCOUNT);
COMMIT;
EXECUTE IMMEDIATE 'SELECT * FROM MovingAverage ORDER BY ID ASC'
BULK COLLECT INTO mrec;
DBMS_OUTPUT.put_line (SQL%ROWCOUNT);
COMMIT;
DBMS_OUTPUT.put_line (total);
RETURN total;
END;
/
Call this function like this.
SET SERVEROUTPUT ON
DECLARE
x NUMBER;
BEGIN
x := totalCustomers;
END;
/
You cannot call the function in SQL select
With collections and the table function, a function can return a table that can be queried in an SQL statement. This is demonstrated in the following example.
Create your record type variable first.
create or replace type t_record as object (i number,n varchar2(30));
Create table type variable which is based on record type variable.
create or replace type t_table as table of t_record;
Then we can proceed to create a function as follows.
create or replace function return_table return t_table as
v_ret t_table;
begin
--
-- Call constructor to create the returned
-- variable:
--
v_ret := t_table();
--
-- Add one record after another to the returned table.
-- Note: the »table« must be extended before adding
-- another record:
--
v_ret.extend; v_ret(v_ret.count) := t_record(1, 'one' );
v_ret.extend; v_ret(v_ret.count) := t_record(2, 'two' );
v_ret.extend; v_ret(v_ret.count) := t_record(3, 'three');
--
-- Return the record:
--
return v_ret;
end return_table;
For more details and further extension of work please refer following URL.
https://renenyffenegger.ch/notes/development/databases/Oracle/PL-SQL/collection-types/return-table-from-function/index
http://www.adp-gmbh.ch/ora/plsql/coll/return_table.html

Creating and using Sequence in Oracle stored procedure - Sequence doesn't exist

DECLARE
v_emp_id NUMBER;
empid NUMBER;
stmt VARCHAR2(1000);
BEGIN
SELECT MAX(emp_id) + 1 INTO v_emp_id FROM employees;
BEGIN
dbms_output.put_line(v_emp_id );
stmt := 'CREATE SEQUENCE emp_seq start with ' ||v_emp_id|| ' increment by 1 NOCYCLE';
EXECUTE IMMEDIATE stmt;
COMMIT;
END;
insert into emp_new select emp_seq.nextval,empname from (select * from employee where active = 0);
dbms_output.put_line(empid);
END;
/
When executing above procedure, I get the following errors
ORA-06550: line 13, column 10:
PL/SQL: ORA-02289: sequence does not exist
ORA-06550: line 13, column 3:
PL/SQL: SQL Statement ignored
But when executing the below procedure, it is successful and sequence is created.
DECLARE
v_emp_id NUMBER;
empid NUMBER;
stmt VARCHAR2(1000);
BEGIN
SELECT MAX(emp_id) + 1 INTO v_emp_id FROM employees;
BEGIN
dbms_output.put_line(v_emp_id );
stmt := 'CREATE SEQUENCE emp_seq start with ' ||v_emp_id|| ' increment by 1 NOCYCLE';
EXECUTE IMMEDIATE stmt;
COMMIT;
END;
dbms_output.put_line(empid);
END;
/
During compile time sequence not exists so compiler returns error. Execute immediate will be executed on runtime but compiler don't know that it will create sequence you called later in code.
create or replace procedure createtest as
begin
execute immediate 'create table t1 (c1 number)';
insert into t1 values (1);
end;
/
Gives the same error as yours as table t1 not exists. So insert statement is invalid. This is error during compilation of PL/SQL.
create table t1 (c1 number);
After that I can create procedure but when I do:
exec createtest;
I got error that table already exists. But compiler didn't knew that I'm trying create again same table so it will be returned on run not during compilation.
If you really need to do it such way please do:
create or replace procedure createtest as
begin
execute immediate 'create table t1 (c1 number)';
execute immediate 'insert into t1 values (1)';
end;
/
In you case:
execute immediate 'SELECT emp_seq.nextval FROM dual' INTO empid;
[EDIT]
What I understand is you want to be sure that sequence is set to max(empid) so please do not try to create it inside procedure. Create sequence once then in procedure body execute:
select max(empid) into maxempid from employee;
select emp_seq.currval into maxseq from dual;
if(empid-maxseq>0) then
execute immediate 'alter sequence emp_seq increment by ' || empid-maxseq;
end if;
You should create sequence statical before you create procedure.
DROP SEQUENCE emp_seq
/
BEGIN
SELECT MAX(emp_id) + 1 INTO v_emp_id FROM employees;
dbms_output.put_line(v_emp_id );
execute immediate 'CREATE SEQUENCE emp_seq start with ' ||v_emp_id|| ' increment by 1 NOCYCLE';
END;
/
and then CREATE OR REPLACE FUNCTION/PROCEDURE/PACKAGE .... which refers to your sequence
Whoever facing this problem, One quick solution is to add below while declaring Procedure;
CREATE OR REPLACE PROCEDURE PROC_NAME AUTHID CURRENT_USER AS
After this declaration EXECUTE IMMEDIATE statement will compile & run successfully.

PL/SQL EXECUTE IMMEDIATE inside LOOP (procedure to truncate all tables in schema)

I need to create procedure which will delete all data from tables in one schema. I try something like that
CREATE OR REPLACE PROCEDURE CLEAR_ALL
IS
sql_truncate VARCHAR2(50);
cursor c1 is
SELECT table_name
FROM all_tables
WHERE owner = 'KARCHUDZ_S';
BEGIN
sql_truncate := 'TRUNCATE TABLE :text_string';
FOR table_name in c1
LOOP
EXECUTE IMMEDIATE sql_truncate USING table_name;
END LOOP;
END CLEAR_ALL;
But it gives me two errors which i cannot understand and fix.
Error(13,7): PL/SQL: Statement ignored
Error(13,44): PLS-00457: Statment must be type of SQL <-- (This error
i had to translate, cause i use University Oracle 11g base which have
Polish lang)
Why not just generate the statement and call it, like this?
CREATE OR REPLACE PROCEDURE CLEAR_ALL
IS
vs_statement VARCHAR2(100);
cursor c1 is
SELECT table_name
FROM all_tables
WHERE owner = 'KARCHUDZ_S';
BEGIN
FOR table_rec in c1
LOOP
vs_statement := 'TRUNCATE TABLE ' || table_rec.table_name;
EXECUTE IMMEDIATE vs_statement;
END LOOP;
END CLEAR_ALL;
You can't use bind variables (i.e. your using clause) as a placeholder for an object name. If you could, you wouldn't need to use dynamic SQL in the first place. You'll have to use concatenation or substitution instead:
CREATE OR REPLACE PROCEDURE CLEAR_ALL
IS
sql_truncate CONSTANT VARCHAR2(50) := 'TRUNCATE TABLE [text_string]';
cursor c1 is
SELECT table_name
FROM all_tables
WHERE owner = 'KARCHUDZ_S';
BEGIN
FOR row in c1
LOOP
EXECUTE IMMEDIATE replace(sql_truncate, '[text_string]', row.table_name);
END LOOP;
END CLEAR_ALL;

Get the count of each table

I was trying to create a procedure to fetch the total count of rows of all tables corresponding to a schema.
I am proceeding with a cursor which store the total list of tables and and the same is iterate further. Even though the functionality is not tested.The procedure creation compiled with the following errors.
create or replace
PROCEDURE PROC_TABLE_COUNT
AS
table_count NUMBER;
CURSOR total_tables
IS
SELECT table_name FROM dba_tables WHERE owner = 'OWNER_NAME';
BEGIN
FOR i IN total_tables
LOOP
SELECT COUNT (*) INTO table_count FROM dba_tables db where db.table_name = i.table_name;
END LOOP;
END PROC_TABLE_COUNT;
1)Error(7,6): PL/SQL: SQL Statement ignored
2)Error(7,33): PL/SQL: ORA-00942: table or view does not exist
3)Error(11,1): PL/SQL: SQL Statement ignored
4)Error(11,76): PL/SQL: ORA-00904: "I"."TABLE_NAME": invalid identifier
5)Error(11,76): PLS-00364: loop index variable 'I' use is invalid
Question 1:
Is the error 2(at dba_tables) is due to the grant being denied? By right clicking on the procedure name ,I tried to assign the privilege to debug and execute. But still the error persists.
Question 2:
Regarding the invalid identifier. Why is this error coming?
UPDATE:
As per one of the valuable comment I have changed the query and the compile error is gone. Now there is an issue in the logic.
create or replace procedure proc_tab_count as
table_count NUMBER;
CURSOR total_tables
IS
SELECT table_name FROM user_tables;
BEGIN
FOR i IN total_tables
LOOP
SELECT COUNT (*) INTO table_count FROM user_tables WHERE db.table_name = i.table_name; --Wrong logic here
DBMS_OUTPUT.put_line(i.table_name||'-COUNT:'||table_count);
END LOOP;
end proc_tab_count;
output is coming like:
Table1 -COUNT:1
Table2 -COUNT:1
Table3 -COUNT:1
Table3 -COUNT:1
Table4 -COUNT:1
Table5 -COUNT:1
Guess, you want to count rows in all your tables, and we need a dynamic SQL here.
EXCEUTE IMMEDIATE is used to frame the dynamic SQL making the OWNER.TABLE_NAME dynamic.
create or replace procedure proc_tab_count as
table_count NUMBER;
CURSOR total_tables
IS
SELECT table_name FROM user_tables;
BEGIN
FOR i IN total_tables
LOOP
/* Handle Exceptions */
BEGIN
EXECUTE IMMEDIATE 'SELECT COUNT (*) FROM '|| i.table_name INTO table_count;
DBMS_OUTPUT.put_line(i.table_name||'-COUNT:'||table_count);
EXCEPTION WHEN OTHERS
THEN
DBMS_OUTPUT.put_line('Error while Querying '||i.table_name||'-Error:'||SQLERRM);
END;
END LOOP;
end proc_tab_count;
I'm not so sure that the accepted answer works. Does user_tables contain owner? Otherwise, it's spot on.
Anyway. Another approach using SYS_REFCURSOR:
CREATE OR REPLACE PROCEDURE proc_table_count
CURSOR total_tables IS
SELECT table_name
FROM user_tables
ORDER BY table_name;
table_count NUMBER;
v_sql VARCHAR2(100);
v_cursor SYS_REFCURSOR;
BEGIN
FOR i IN total_tables
LOOP
BEGIN
v_sql := 'SELECT COUNT (*) FROM '||i.table_name;
OPEN v_cursor FOR v_sql;
FETCH v_cursor INTO table_count;
CLOSE v_cursor;
DBMS_OUTPUT.put_line(i.table_name||'-COUNT:'||table_count);
EXCEPTION WHEN OTHERS
THEN
DBMS_OUTPUT.put_line('Error while Querying '||i.table_name||'-Error:'||SQLERRM);
END;
END LOOP;
end proc_tab_count;

using pl/sql to update sequences

We have a sql script to update a set of sequences after seed data populated our tables. The code below would not work:
declare
cursor c1 is
select
'select nvl(max(id),0) from '||uc.table_name sql_text,
uc.table_name||'_SEQ' sequence_name
from
user_constraints uc,
user_cons_columns ucc
where uc.constraint_type='P'
and ucc.constraint_name = uc.constraint_name
and ucc.column_name='ID'
and uc.owner='ME';
alter_sequence_text varchar2(1024);
TYPE generic_cursor_type IS REF CURSOR;
max_id number;
c2 generic_cursor_type;
begin
for r1 in c1 loop
open c2 for r1.sql_text;
fetch c2 into max_id;
close c2;
if( max_id != 0 ) then
dbms_output.put_line( 'seq name = '||r1.sequence_name );
execute immediate 'alter sequence '||r1.sequence_name||' increment by '||to_char(max_id);
dbms_output.put_line( 'max_id = '||to_char(max_id) );
execute immediate 'select '||r1.sequence_name||'.nextval from dual';
dbms_output.put_line( 'sequence value = '||to_char(next_id) );
execute immediate 'alter sequence '||r1.sequence_name||' increment by 1';
dbms_output.put_line( 'sequence: '||r1.sequence_name||' is at '||to_char(max_id+1) );
end if;
end loop;
end;
After searching I found a reference that stated I needed to change the line:
execute immediate 'select '||r1.sequence_name||'.nextval from dual'
and add 'into next_id;' (of course declaring next_id appropriately) so the result would be:
execute immediate 'select '||r1.sequence_name||'.nextval from dual into next_id;
I've only dealt lightly with pl/sql and sql in general and am interested to know why this change was necessary to make the script work correctly.
Thanks.
When you are using select inside PL/SQL block you have to place data returned by that select statement somewhere. So you have to declare a variable of appropriate data type and use select into clause to put data select returns into that variable even if select statement is executed by execute immediate statement.
Examples
declare
x number;
begin
select count(*)
into x
from all_objects;
end;
declare
x number;
begin
execute immediate 'select count(*)from all_objects' into x;
end;
So your execute immediate statement would be
execute immediate 'select '||sequence_name||'.nextval from dual' into newseqval;
If you are using Oracle 11g onward you can assign sequence's value directly to a variable, there is no need of using select into clause.
declare
x number;
begin
x := Sequence_Name.nextval;
end;
select seq_name.nextval from dual implies the implicit cursor creation and the results of the cursor should be fetched somewhere so you need fetch it into any externally declared bind variable.

Resources