1. We have moved to a new forum! There may be a few things not working properly so please let us know if you find a bug. Remember to use the bbCode [ sql ] tag for SQL statements.

How to pull data from several tables that follows a pattern?

Discussion in 'SQL - Questions and Answers' started by Christian, May 31, 2006.

  1. Christian Guest

    Dialect: Oracle
    How do I pull data from several tables into one, where the table name follow a certain pattern:

    EX_001
    EX_002
    EX_003
    ..
    ..
    EX_N

    Where new tables can be added continually in the same pattern - and this data also should be included in the SQL?
  2. Dimitar Guest

    Dialect: Oracle
    Oracle provides Dynamic SQL facilities that would be the basis for a solution.
    The main points:
    1. You create a "for ... loop ... end loop" to iterate over the table names that follow the pattern.
    2. Inside the loop (for each table) you append a sql "select ..." text to form a union of the data in all tables.
    3. At the end you execute the constructed sql text.

    There can be variations of this solution. You could use the "execute immediate .." construct or the dbms_sql facility.
    Or, instead of concatenating, inside the loop you could actually execute the single-table sql.

    Hope this helps.

    P.S.
    SQL:

    for t in (SELECT object_name FROM user_objects WHERE object_type='TABLE' and object_name like 'ex_%')
    loop
    ...
    end loop

Share This Page