Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to select from multiples tables, having theirs names as the result of a subquery?

Tags:

sql

oracle

I have some tables with the same structure and I want to make a select in a group of them.

Rather than just making a loop to all of those tables, I would like to put a subquery after the FROM of the main query.

Is it possible or it will fail?

Thanks!

(Using Oracle)


Additional info: I don't have the name of the table right away! They're stored in another table. Is it possible to have a subquery that I could put after the FROM of my main query?

like image 430
Acibi Avatar asked Dec 07 '22 02:12

Acibi


2 Answers

"I don't have the name of the table right away! They're stored in another table"

Oracle doesn't do this sort of thing in SQL. You'll need to use PL/SQL and assemble a dynamic query.

create or replace function get_dynamic_rows
    return sys_refcursor
is
    stmt varchar2(32767) := null;
    return_value sys_refcursor;
begin
    for r in ( select table_name from your_table ) 
    loop
        if stmt is not null then
           stmt := stmt||' union all ';
        end if;
        stmt := stmt||'select * from '||r.table_name;
    end loop;
    open return_value for stmt;
    return return_value;

end;
/

This will assemble a query like this

select * from table_1 union all select * from table_2

The UNION ALL is a set operator which combines the output of several queries in a single result set without removing duplicates. The columns in each query must match in number and datatype.

Because the generated statement will be executed automatically there's no real value in formatting it (unless the actual bits of the query are more complicated and you perhaps need to debug it).

Ref Cursors are PL/SQL contructs equivalent to JDBC or .Net ResultSets. Find out more.

like image 81
APC Avatar answered Jan 05 '23 16:01

APC


Sure, just union them together:

select * from TableA
union all
select * from TableB
union all
select * from TableC

You can union in a subquery:

select *
from (
    select * from TableA
    union all
    select * from TableB
) sub
where col1 = 'value1'

Use union if you're only interested in unique rows, and union all if you want all rows including duplicates.

like image 25
Andomar Avatar answered Jan 05 '23 14:01

Andomar