开发者

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

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 i开发者_Python百科n another table. Is it possible to have a subquery that I could put after the FROM of my main query?


"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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜