Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get table object by name? (Oracle SQL)

I was trying to find a specific subset of result tables in my database by querying for tables by name and then querying inside those tables.

I know I can get a list of tables like this:

SELECT table_name FROM all_tables WHERE table_name LIKE 'MY_RESULTS_%'

But what I can't figure out is how to use that list in another select statement. For example, I'd like to do something like this:

-- DOESN'T WORK --
SELECT table_name FROM all_tables
WHERE table_name LIKE 'OUTPUTDATA_%'
AND get_table_by_name(table_name).my_value_col = 'Special Value';

This is on an Oracle database with SQL Developer.

like image 942
Didjit Avatar asked Nov 16 '25 19:11

Didjit


1 Answers

Uese Dynamic SQL with a cursor:

DECLARE
  CURSOR all_tables IS
    SELECT table_name
            FROM all_tables 
            WHERE TABLE_NAME like 'MY_RESULTS_%' 
            ORDER BY TABLE_NAME ;
row_count pls_integer;
BEGIN
  FOR rslt IN all_tables LOOP
    EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ' 
     || rslt.TABLE_NAME || ' where ' 
     ||rslt.TABLE_NAME||'.my_value_col= ''Special Value''' INTO row_count;
  --here if the specific table.specificcolumn has the specific value print it  
  if row_count>=1 THEN
     BEGIN
       DBMS_OUTPUT.PUT_LINE(rslt.TABLE_NAME);
     END;
  END IF;
  END LOOP;
END;
like image 104
nil Avatar answered Nov 19 '25 09:11

nil