ORACLE SQL CURSOR / FOR LOOP - sql

I need to verify converted data, distinct values and records counts. I would like to write statements so that I can enter a table name, then retrieve it's columns and use them in a query to get its distinct values (the actual values, not just a count of how many distinct) and their count.
I think I need to a CURSOR or CURSOR FOR LOOP and create something like this:
declare
cursor field_name
is
select COLUMN_NAME
from user_tab_cols
where table_name='TABLE1'
c_field_name field_name%ROWTYPE;
BEGIN
OPEN field_name
loop
fetch field_name INTO c_field_name;
exit when field_name%NOTFOUND;
end loop;
CLOSE field_name;
end;
Then run a query using that above in something like
select field_name, count(*)
from table1
group by field_name
Do I need to create 2 loop statements? I've not yet created one and can't quite get the context to get my results so far.

BEGIN
FOR myrow in (select field_name, count(*) as "count" from table1 group by field_name)
loop
dbms_output.put_line(myrow.field_name);
dbms_output.put_line(myrow.count);
end loop;
end;

Considering you will be giving the table name as parameter below code will print all the values of all the columns one by one along with the count of the values
create or replace PROCEDURE PR_PREP(
P_TABLE_NAME IN VARCHAR2)
IS
CURSOR CUR_COLUMNS (PA_TABLE_NAME VARCHAR2)
IS
SELECT COLUMN_NAME FROM ALL_TAB_COLUMNS WHERE TABLE_NAME = PA_TABLE_NAME;
COL_NAMES CUR_COLUMNS%ROWTYPE;
TYPE TYP_RECORD
IS
RECORD
(
FIELD_NAME VARCHAR2(255),
CNT INT);
TYPE TYP_OP_TABLE
IS
TABLE OF TYP_RECORD;
OP_TABLE TYP_OP_TABLE;
I INT;
V_SQL VARCHAR2(2000);
BEGIN
FOR COL_NAMES IN CUR_COLUMNS(P_TABLE_NAME)
LOOP
V_SQL := 'SELECT ' || COL_NAMES.COLUMN_NAME || ' AS FIELD_NAME ,
COUNT(*) AS CNT FROM ' ||
P_TABLE_NAME || ' GROUP BY ' || COL_NAMES.COLUMN_NAME ;
-- DBMS_OUTPUT.PUT_LINE (V_SQL);
EXECUTE IMMEDIATE V_SQL BULK COLLECT INTO OP_TABLE;
dbms_output.put_line('columna name = ' ||COL_NAMES.COLUMN_NAME);
FOR I IN OP_TABLE.FIRST .. OP_TABLE.LAST
LOOP
DBMS_OUTPUT.PUT_LINE('FIELD VALUE '||OP_TABLE(I).FIELD_NAME || ' COUNT = ' || OP_TABLE(I).CNT);
END LOOP;
DBMS_OUTPUT.PUT_LINE('ONE FILED ENDED , NEXT STARTED');
END LOOP;
END;

Related

Oracle procedure to delete records in all tables of an owner

I am trying to create an Oracle procedure to delete records from multiple tables of an owner based upon a distinct count condition:
Firstly I am trying to obtain the tables for which I want to delete those records with this query:
SELECT * FROM ALL_TABLES WHERE OWNER = 'Lorik' AND TABLE_NAME LIKE 'UT_%';
This results in a total of 300 tables, now all of those tables have a column named: DATE_INC
I am trying to delete records from all of the tables if this COUNT(DISTINCT DATE_INC) > 5.
Assuming that one of those 300 tables is named UT_NAMES:
SELECT COUNT(DISTINCT DATE_INC) FROM Lorik.UT_NAMES;
So if the count exceeds 5, then I want to delete the records with the minimum date:
DELETE MIN(DATE_INC) FROM Lorik.UT_NAMES;
Can someone please link these steps together so I can loop through each table of that owner and obtain the distinct date count and delete records based upon the above cited condition.
Thanks in advance!
You can use 'EXECUTE IMMEDIATE' in PL/SQL to accomplish your goal:
DECLARE
strTable VARCHAR2(32767);
nCount NUMBER;
BEGIN
FOR aRow IN (SELECT *
FROM ALL_TABLES
WHERE OWNER = 'Lorik' AND
TABLE_NAME LIKE 'UT_%')
LOOP
strTable := aRow.OWNER || '.' || aRow.TABLE_NAME;
EXECUTE IMMEDIATE 'SELECT COUNT(DISTINCT DATE_INC) FROM ' || strTable
INTO nCount;
IF nCount > 5 THEN
EXECUTE IMMEDIATE 'DELETE FROM ' || strTable ||
' WHERE DATE_INC = (SELECT MIN(DATE_INC) ' ||
'FROM ' || strTable || ')';
END IF;
END LOOP;
END;
Not tested on animals - you'll be first! :-)
As pointed out by #Andrew this seems to be very basic processes.
Declare some variables.
Open a cursor.
Use dynamic sql to count
Use dynamic sql to delete
Add some log information
_
declare
v_cnt number;
v_sql varchar2(1000);
begin
for cur in (SELECT * FROM ALL_TABLES WHERE OWNER = 'HR' AND TABLE_NAME LIKE 'E%')
loop
v_sql := 'select count(distinct department_id||''date_inc'') from '||cur.owner||'. '||cur.table_name;
execute immediate v_sql into v_cnt;
dbms_output.put_line (cur.table_name || ': ' || v_cnt);
if v_cnt > 5 then
v_sql := 'delete from '||cur.owner||'. '||cur.table_name || ' where date_inc = (select min (date_inc) from ' ||cur.owner||'. '||cur.table_name || ')';
dbms_output.put_line (v_sql);
-- execute immediate v_sql;
end if;
end loop;
rollback;
-- commit;
end;
A little bit simpler dynamic SQL for deleting rows, as it uses a local variable:
declare
l_cnt number; -- counter variable
l_min_date date; -- MIN(date_inc)
begin
for cur_t in (select table_name from all_tables
where owner = 'Lorik' -- are you sure it is not uppercase, LORIK?
and table_name like 'UT%' -- underline is wildcard character so you don't need it
)
loop
execute immediate 'select count(distinct date_inc), min(date_inc) from ' ||
cur_t.table_name into l_cnt, l_min_date;
if l_cnt > 5 then
execute immediate 'delete from ' || cur_t.table_name ||
' where date_inc = ' || l_min_date_inc;
end if;
end loop;
end;
/

List columns of table on which there is at least one row with a non null value for a specific query

I'm trying to find the proper query to :
Get all the column names of a table on which there is at least one row with a non null value for a specific query.
Meaning : I will see which columns have at least one value set in the record returned by my given query.
I hope I'm clear enough.
I think you need something as the following:
SELECT CASE WHEN MAX(col1) IS NOT NULL THEN 'COL1' END ||','
|| CASE WHEN MAX(col2) IS NOT NULL THEN 'COL2' END ||','
...
FROM T
Then use REGEXP_REPLACE to replace duplicated ,. You can use user_tab_columns to generate this query dynamically as mentioned.
Please check below anonymous block for your case , tablename should be given at 3 places in below query
Declare
v_columnlist varchar2(32627);
v_noofcolumns number;
Columnnm varchar2(1000);
Finalcolumns varchar2(32627);
v_count number:=0;
plsql_block varchar2(32627);
Begin
select LISTAGG(column_name,',') within group (order by column_id),max(column_id)
into v_columnlist , v_noofcolumns
from user_tab_columns
where table_name='tablename';
FOR Lcntr IN 1..v_noofcolumns
LOOP
select REGEXP_SUBSTR(v_columnlist,'[^,]+',1,Lcntr)
into Columnnm
from dual;
plsql_block := 'select count(*) from tablename where '|| Columnnm || ' is not null ';
EXECUTE IMMEDIATE plsql_block into v_count;
IF v_count > 1 THEN
Finalcolumns:= LTRIM(Finalcolumns ||','||Columnnm,',');
END IF;
END LOOP;
plsql_block := 'select ' || Finalcolumns ||' from tablename ';
DBMS_OUTPUT.PUT_LINE(plsql_block);
END;

Dynamic Oracle Procedure - issue with structure

I seem to be having some issues around creating a stored procedure and I simply cannot see where the issue lies. I am relatively new to Oracle.
I have a table of unknown length. What I have done is I created a stored procedure that will create a table to the width of the row count of the table where I am getting my values from. i.e. if the table has 10 values, the code will create a new table 10 columns wide, etc.
I have managed to get the initial code working, but now I am trying to add some additional logic without success.
My logic that I am trying to accomplish is as such:
IF TABLE DOES NOT EXIST - CREATE IT
IF TABLE EXSITS - SIMPLY INSERT INTO IT
I have not created the code for the INSERT part yet as I cannot get the first part to work. Everything was working fine until I added the count and IF statement.
CREATE OR REPLACE PROCEDURE "MDWPROD"."WORKFLOW_VAR_PIVOT" IS
v_sql varchar2(32767);
-- for the first run ofthe procedure, we need to create the table
DECLARE var_count INT;
SELECT
COUNT(*)
INTO
var_count
FROM
all_tables
WHERE
OWNER = 'MDWPROD'
AND TABLE_NAME = 'RBI_PROCESSVARIABLE_WK';
-- if var_count = 0 then the table does not exists, create it, otherwise proceed with other logic
IF var_count = 0 THEN
-- cursor to find out the maximum number of projected columns required
CURSOR cur_proj_test IS
SELECT DISTINCT
ID,
VARIABLE_REPORT_LBL
FROM
MDWPROD.RBI_VARIABLETYPE_DM
ORDER BY
ID;
-- We now loop through the cursor, and build of the SQL string to CREATE and POPULATE the table
BEGIN
v_sql := 'CREATE TABLE MDWPROD.RBI_PROCESSVARIABLE_WK AS SELECT VAR.PROCESS_ID';
FOR i IN cur_proj_test
LOOP
-- dynamically add to the projection for the query
v_sql := v_sql || ',MAX(CASE VT.VARIABLE_REPORT_LBL WHEN ''' || i.VARIABLE_REPORT_LBL || ''' THEN VAR.VALUE ELSE '''' END) AS "' || i.VARIABLE_REPORT_LBL || '"';
END LOOP;
v_sql := v_sql || ' FROM MDWPROD.RBI_VARIABLE_DM VAR INNER JOIN MDWPROD.RBI_VARIABLETYPE_DM VT ON VAR.VARIABLE_TYPE_ID = VT.ID WHERE VAR.CURRENT_IND = ''Y'' GROUP BY VAR.PROCESS_ID order by VAR.PROCESS_ID';
-- Create table and populate it with all the relevant variable values
EXECUTE IMMEDIATE v_sql;
END;
END IF;
END;
Any assistance would be greatly appreciated.
Original working proc:
CREATE OR REPLACE PROCEDURE WORKFLOW_VAR_PIVOT IS
v_sql varchar2(32767);
-- cursor to find out the maximum number of projected columns required
CURSOR cur_proj_test IS
SELECT DISTINCT
ID,
VARIABLE_REPORT_LBL
FROM
MDWPROD.RBI_VARIABLETYPE_DM
ORDER BY
ID;
-- We now loop through the cursor, and build of the SQL string to CREATE and POPULATE the table
BEGIN
v_sql := 'CREATE TABLE MDWPROD.RBI_PROCESSVARIABLE AS SELECT VAR.PROCESS_ID';
FOR i IN cur_proj_test
LOOP
-- dynamically add to the projection for the query
v_sql := v_sql || ',MAX(CASE VT.VARIABLE_REPORT_LBL WHEN ''' || i.VARIABLE_REPORT_LBL || ''' THEN VAR.VALUE ELSE '''' END) AS "' || i.VARIABLE_REPORT_LBL || '"';
END LOOP;
v_sql := v_sql || ' FROM MDWPROD.RBI_VARIABLE_DM VAR INNER JOIN MDWPROD.RBI_VARIABLETYPE_DM VT ON VAR.VARIABLE_TYPE_ID = VT.ID WHERE VAR.CURRENT_IND = ''Y'' GROUP BY VAR.PROCESS_ID order by VAR.PROCESS_ID';
-- un comment this line to print out the entire SQL statement
-- dbms_output.put_line('Dynamic SQL Statement:-' || chr(10) || v_sql || chr(10) || chr(10));
-- DROP TABLE before recreating it
EXECUTE IMMEDIATE 'DROP TABLE MDWPROD.RBI_PROCESSVARIABLE';
-- Create table and populate it with all the relevant variable values
EXECUTE IMMEDIATE v_sql;
END;
There may be other problems (you never stated your exact error), but I can immediately see that the begin keyword is in the wrong place. Your declarations should be at the top, before the begin keyword, and your execution statements should come after.
I moved things around a little. This should get you closer to your goal:
CREATE OR REPLACE PROCEDURE "MDWPROD"."WORKFLOW_VAR_PIVOT" IS
v_sql varchar2(32767);
-- for the first run ofthe procedure, we need to create the table
DECLARE var_count INT;
-- cursor to find out the maximum number of projected columns required
CURSOR cur_proj_test IS
SELECT DISTINCT
ID,
VARIABLE_REPORT_LBL
FROM
MDWPROD.RBI_VARIABLETYPE_DM
ORDER BY
ID;
BEGIN
SELECT
COUNT(*)
INTO
var_count
FROM
all_tables
WHERE
OWNER = 'MDWPROD'
AND TABLE_NAME = 'RBI_PROCESSVARIABLE_WK';
-- if var_count = 0 then the table does not exists, create it, otherwise proceed with other logic
IF var_count = 0 THEN
-- We now loop through the cursor, and build of the SQL string to CREATE and POPULATE the table
v_sql := 'CREATE TABLE MDWPROD.RBI_PROCESSVARIABLE_WK AS SELECT VAR.PROCESS_ID';
FOR i IN cur_proj_test
LOOP
-- dynamically add to the projection for the query
v_sql := v_sql || ',MAX(CASE VT.VARIABLE_REPORT_LBL WHEN ''' || i.VARIABLE_REPORT_LBL || ''' THEN VAR.VALUE ELSE '''' END) AS "' || i.VARIABLE_REPORT_LBL || '"';
END LOOP;
v_sql := v_sql || ' FROM MDWPROD.RBI_VARIABLE_DM VAR INNER JOIN MDWPROD.RBI_VARIABLETYPE_DM VT ON VAR.VARIABLE_TYPE_ID = VT.ID WHERE VAR.CURRENT_IND = ''Y'' GROUP BY VAR.PROCESS_ID order by VAR.PROCESS_ID';
-- Create table and populate it with all the relevant variable values
EXECUTE IMMEDIATE v_sql;
END IF;
END;

Loop through a list of table columns, and apply a query to them

We have our table mytable, that contains columns: id, value, description....
Now I want to apply this sql query to each column:
select distinct [column] from mytable;
Is there a way to do this?
nb. I want to provide the list of columns to loop through, rather than looping through every column in the table.
declare
l_tab_name varchar2(32) := 'MY_TABLE';
begin
for c1 in (select t.column_name from user_tab_columns t where t.table_name = l_tab_name)
loop
execute immediate 'select distinct ' || c1.column_name || ' from ' || l_tab_name;
end loop;
end;

query each column of a table in a loop - Oracle Database

I'm working with an oracle database and what I basically need to do is to count the number of NULL fields per column in a certain table.
something like that:
DECLARE
BlankCount number(20);
i number(2) := 1;
BEGIN
loop that would take each column individualy and exit after the last one
SELECT COUNT(*) INTO BlankCount FROM name_of_my_table
DBMS_OUTPUT.PUT_LINE('Column '||i||' has '||BlankCount||' empty cells');
i := i + 1;
END LOOP;
END;
I just couldn't find anything that would do the loop part.
It would also be nice if instead of just numbering them (with the i) I could display the column name (but that is not very important).
Thank you!
Something like this:
declare
mytable varchar(32) := 'MY_TABLE';
cursor s1 (mytable varchar2) is
select column_name
from user_tab_columns
where table_name = mytable
and nullable = 'Y';
mycolumn varchar2(32);
query_str varchar2(100);
mycount number;
begin
open s1 (mytable);
loop
fetch s1 into mycolumn;
exit when s1%NOTFOUND;
query_str := 'select count(*) from ' || mytable || ' where ' || mycolumn || ' is null';
execute immediate query_str into mycount;
dbms_output.put_line('Column ' || mycolumn || ' has ' || mycount || ' null values');
end loop;
end;
Try using cursor approach and Dynamic SQL as mentioned in this thread: How to loop through columns in an oracle pl/sql cursor
HTH.