Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through the result of a PLSQL Select

Tags:

loops

sql

plsql

I am trying to find how many occurrences of a particular value there are in a particular column in an Oracle database. The column is used in dozens of tables and I'm going to have to run the queries many times, so I don't want to query each table individually. I can get a list of the tables to search with something like:

Select table_name from all_tab_cols
   join all_tables using (table_name)
   where column_name = 'EmployeeId' and num_rows > 0

The next step is to iterate through that list of table names and output each table that contains a particular value in the EmployeeId column. For example, output might be something like:

**Table Name   Column_name   # Rows for EmployeeId = '123456'**
Table 1        EmployeeId                    1
Table 2        EmployeeId                   12
etc.

I'm not a developer and don't have experience using cursors in SQL scripts, so any help would be greatly appreciated.

like image 566
1earldog Avatar asked Apr 03 '18 16:04

1earldog


People also ask

Can we use loop in SELECT statement?

The for-loop-name can be used to qualify the column names in the result set as returned by the select-statement. The cursor-name simply names the cursor that is used to select the rows from the result set.

How can I see the results in PL SQL?

To do this we use a procedure called dbms_output. put_line to place the results in a buffer that SQL*Plus will retrieve and display. SQL*Plus must be told to retrieve data from this buffer in order to display the results. The SQL*Plus command 'set serveroutput on' causes SQL*Plus to retrieve and display the buffer.

How does FOR LOOP work in PL SQL?

The LOOP statement executes a sequence of statements within a PL/SQL code block multiple times. The WHILE statement repeats a set of SQL statements as long as a specified expression is true. The condition is evaluated immediately before each entry into the loop body.


1 Answers

try using CURSOR FOR LOOP.

Probably it may look as shown below (not tried).

BEGIN
FOR item IN
(Select table_name,column_name,num_rows  from all_tab_cols
   join all_tables using (table_name)
   where column_name = 'EmployeeId' and num_rows > 0)
LOOP
DBMS_OUTPUT.PUT_LINE
(item.table_name || '    ' || item.column_name ||'    '||item.num_rows);
END LOOP;
END;
like image 71
Pavan Chandaka Avatar answered Sep 20 '22 21:09

Pavan Chandaka