Using a derived table name in a select ...

In SQL or PL/SQL am I able to use the derived value of a colu,n (which holds a table name) to run an SQL.
Basically I want to perform a "select count(*) from table" where table is a list of tables held in another, eg all_tables.
EG:
all_tables has
TABLE1
TABLE2
TABLE3
and I want to get
TABLE1 100
TABLE2 50
TABLE3 110
Thanks

SQL> ed
Wrote file afiedt.buf
  1  declare
  2    cursor cur_tables is
  3      select table_name
  4      from user_tables;
  5    v_cnt NUMBER;
  6  begin
  7    for t in cur_tables
  8    loop
  9      execute immediate 'select count(*) from '||t.table_name into v_cnt;
10      dbms_output.put_line('Table: '||t.table_name||' ('||v_cnt||')');
11    end loop;
12* end;
SQL> /
Table: PRE_MAP_LOG (150935)
Table: LOG_SRC (126)
Table: SRC_LOOKUP (10)
Table: T (1)
Table: MYDONORS (22)
Table: CHANGE_LOG (347)
Table: CHANGE_VARCHAR2 (461)
Table: DO_MAP_LOG (50)
Table: CHANGE_DATE (96)
Table: CHANGE_NUMBER (561)
PL/SQL procedure successfully completed.

Similar Messages

  • How can i pass a variable instead of a table name in the Select statement.

    Dear all
    how can i pass a variable instead of a table name in a select statement ?
    Example :-
    Begin
    P_get_procedure_tname (aap_name,otable_name);--It will take an application name and will return a table name
    Select col1 into ocol1
    from  ---- here i want to pass the variable OTABLE_NAME
    End;How can i pass this ?

    Hi,
    You can use dynamic sql.
    EXECUTE IMMEDIATE 'SELECT COL1 INTO ' || OCOL1 || ' FROM " || OTABLE_NAME;
    {code}
    cheers
    VT                                                                                                                                                                                                                                                                                                   

  • How to use a table name in the select statement using a variable?

    Hi Everybody,
                       I got a internal table which has a field or a variable that gets me some tables names. Now I need to retrieve the data from all these tables in that field dynamically at runtime. So could you suggest me a way out to use the select query which uses this variable as a table ?
    Regards,
    Mallik.

    Hi all,
    Actually i need some more clarification. How to use the same select statement, if i've to use the tabname in the where clause too?
    for ex : select * from (tab_name) where....?
    Can we do inner join on such select statements? If so how?
    Thanks & Regards,
    Mallik.

  • Using dymanic table name for running select queries

    Hi there. Currently got a problem with performing the following task:
         Perform fulltext search on all tables that have created fulltext indexes in specific schema. Result should look like this:
              <TABLE_NAME1>                <ID_FROM_TABLE>
              <TABLE_NAME1>                <ID_FROM_TABLE>
              <TABLE_NAME2>                <ID_FROM_TABLE>
              <TABLE_NAME2>                <ID_FROM_TABLE>
         At the moment all tables have the same ID column UOI_ID.
    What I've tried so far is the following:
    PROCEDURE "tuser"."dam.test.db.procedures::textSearch" ( in keyword NVARCHAR(300), out search_results "tuser"."dam.test.db::tuser.procedures.tt_search_results" )
      LANGUAGE SQLSCRIPT
      SQL SECURITY INVOKER
      DEFAULT SCHEMA "tuser"
      AS
    BEGIN
      Write your procedure logic
      DECLARE counter Integer := 1;
      DECLARE row_count Integer;
      DECLARE table_name NVARCHAR(300);
      DECLARE schema_name NVARCHAR(300) := 'tuser';
      indexed_tables = SELECT row_number() OVER (ORDER BY "TABLE_NAME") AS ROW_NUMBER, "TABLE_NAME"
           FROM (
                SELECT DISTINCT "TABLE_NAME"
                     FROM "SYS"."FULLTEXT_INDEXES"
                          WHERE "SCHEMA_NAME" = :schema_name
      SELECT COUNT(*) INTO row_count FROM :indexed_tables;
      WHILE counter < row_count + 1 DO
           SELECT '"tuser"."'||"TABLE_NAME"||'"' INTO table_name FROM :indexed_tables WHERE "ROW_NUMBER" = :counter;
           temporary_results = SELECT :table_name AS TABLE_NAME, "OUI_ID" AS ID
                FROM :table_name
                     WHERE contains(*, :keyword, fuzzy(0.5));
           search_results = CE_UNION_ALL(:search_results, :temporary_results);
           counter := counter + 1;
      END WHILE;
    END;
    At this point it's impossible to perform the:
    ... FROM :table_name ...
    The error is:
    Could not create catalog object: scalar type is not allowed
    Tried doing it with CE functions.
    temporary_table = CE_COLUMN_TABLE(table_name);
    The error is:
    Dependent object not found: SqlScript; tuser.TABLE_NAME
    So the question is: How to dynamically put table name into "FROM ..." statement?

    Hello. Thx for response.
    I have tried something like
    exec 'INSERT INTO "tuser"."dam.test.db::tuser.procedures.search_result" SELECT '''||table_name||''' AS TABLE_NAME, '||column_name||' AS ID, SCORE() AS SCORE  FROM '||table_name||' WHERE contains(*, '''||keyword||''', fuzzy(0.5))';
    but here i have "tuser"."dam.test.db::tuser.procedures.search_result" created before the execution. What i really want is to make it as a local variable. Something like:
    DECLARE schema_name NVARCHAR(300) := 'tuser';
    indexed_tables = SELECT DISTINCT "TABLE_NAME" FROM "SYS"."FULLTEXT_INDEXES" WHERE "SCHEMA_NAME" = :schema_name ;
    but i can not transform the top 'exec ...' statement into 'result = SELECT ...' because it always says that it can not pass the scalar value into the 'FROM ...' part.

  • * table name in the select statements

    Hi,
      I have come across a select Statement as below.
    Select * into *nast from nast where <conditions>.. End select.
    what does this *nast represents and when is it used. why do we need to call a Table  with *<Table Name>
    Kind Regards,
    Usha

    hi,
    select statement will always points to a database table so we have to give database table name and it gets data from that table. for storing that data we have to use internal tables must have same structure of database table.
    so select statement has the following form as........
    select * from [dbtable] into table [internal table]
    endselect.
    in sap select will act as a loop so that we hav to use end sleect. select has different varities in sap. for some types no need of end select.
    for ex:
    select single *
    select * ..................... into table [internal table name].....
    if helpful reward some points.
    with regards,
    suresh.

  • Variable table name in the select statment ?

    data: h_itab like hier_out occurs 0 with header line,
          table_name(30) type C.
    here i declare h_itab as the variable for the table name
    itab_name = input_name
    input_name is imported
    select * from table_name
           into table h_itab
           where OBJVERS = 'A'.
    it does not allow me to use table_name in the select statement i get the error 'table_name is not defined i the abap dictionary as a table, projection view or database view'.
    Any suggestions are highly appreciated.
    Thanks in advance,
    BWer

    Hi,
    You must enclose the name of the table in braces to let the compiler know that the value will be supplied at run time.
    For example -
    tables mara.
    data table_name(30) type c.
    table_name = 'MARA'.
    SELECT *
      FROM (table_name)
    endselect.
    Regards,
    Anand Mandalika.

  • Using variable as table name in pl/sql query - Is possible?

    I am relatively new to PL/SQL and I am trying to create a function that accepts a table name and a rowid as arguments and returns a comma-delimited record string of the values of the table/rowid being passed. The problem is , I cannot code a select stmt as follows
    SELECT * FROM v_table_name
    WHERE rowid = v_row_id
    in PL/SQL. There must be a easy way to approach this.
    Thanks for any and all advice.
    GC

    I don't understand the use of the concat symbol along with the commas and field namesYou just need (if you really need it) to create variable which contains you column separated by comma:
    Simple example (in the second case separate variables are used to create
    the list of columns):
    SQL> declare
      2   rc sys_refcursor;
      3   cols varchar2(200) := 'ename, empno, sal';
      4   tab varchar2(30) := 'emp';
      5  begin
      6   open rc for 'select ' || cols || ' from ' || tab;
      7   close rc;
      8  end;
      9  /
    PL/SQL procedure successfully completed.
    SQL> declare
      2   rc sys_refcursor;
      3 
      4   ename_col varchar2(10) := 'ename';
      5 
      6   empno_col varchar2(10) := 'empno';
      7 
      8   sal_col varchar2(10) := 'sal';
      9 
    10   tab varchar2(30) := 'emp';
    11 
    12  begin
    13 
    14   open rc for 'select ' || ename_col || ',' || empno_col || ',' || sal_col ||
    15   ' from ' || tab;
    16 
    17   close rc;
    18  end;
    19  /
    PL/SQL procedure successfully completed.Rgds.

  • How to use full qualified table names in RPD

    Hi,
    We are implementing the BI Financial Analytics, we have a requirement to use diffrent user accounts for DAC , ETL and OBIEE
    DAC, ETL we are using user as XXOBI
    For OBIEE RPD we have to use user with read only access such as XXOBI_APP
    How can i make the changed to BI server / RPD to use full qualified names.
    I have tried to select the Full Qualified table name property in Oracle Datawarehouse connection pool setting.
    If i enable that all my sql query is showing tables as catalog.dbo.w_party_d ( my tables in physical layer showing under catalaog -> dbo -> all tables and joins)
    Any help in this is appreciated.
    Thanks
    Kris

    kmangamuri wrote:
    Hi,
    We are implementing the BI Financial Analytics, we have a requirement to use diffrent user accounts for DAC , ETL and OBIEE
    DAC, ETL we are using user as XXOBI
    For OBIEE RPD we have to use user with read only access such as XXOBI_APP
    How can i make the changed to BI server / RPD to use full qualified names.
    I have tried to select the Full Qualified table name property in Oracle Datawarehouse connection pool setting.
    If i enable that all my sql query is showing tables as catalog.dbo.w_party_d ( my tables in physical layer showing under catalaog -> dbo -> all tables and joins)
    Any help in this is appreciated.
    Thanks
    KrisAre you saying you just need to access the database using different accounts? If that is the case, why dont you just update the connection pool settings like username and password with XXOBI_APP account which you are supposed to be using for OBIEE?

  • Using variables as table names. Ideas for alternative designs

    Hi,
    I am designing an application which uses synonyms to pull information from 'client' DBs via DB Links. The synonyms are created with a DB_ID in the name (example: CUSTOMER_100, CUSTOMER_200... where 100 and 200 are DB IDs from 2 separate client DBs.
    I have a procedure which selects data from the synonym based on what DB_ID is passed to the procedure. I want to be able to run this one procedure for any DB_ID that is entered. I am now aware I cannot use variable names for table names and using EXECUTE IMMEDIATE doesnt seem to fit for what I am trying to do.
    Does anybody have any suggestions or re-design options I could use to achieve this generic procedure that will select from a certain synonym based on the DB info input parameters? Thanks.
    CREATE OR REPLACE PROCEDURE CUSTOMER_TEST(p_host IN VARCHAR2, p_db_name IN VARCHAR2, p_schema IN VARCHAR)
    IS
       v_hostname     VARCHAR2 (50) := UPPER (p_host);
       v_instance     VARCHAR2 (50) := UPPER (p_db_name);
       v_schema     VARCHAR2 (50) := UPPER (p_schema);
       v_db_id  NUMBER;  
       v_synonym VARCHAR2(50);
       CURSOR insert_customer
       IS
         SELECT 
           c.customer_fname,
           c.customer_lname
         FROM v_synonym_name c;
    BEGIN
    -- GET DB_ID BASED ON INPUT PARAMETERS       
      select d.db_id
      into v_db_id
      from  t_mv_db_accounts ac,
      t_mv_db_instances i,
       t_mv_dbs d,
       t_mv_hosts h
      where ac.db_ID = d.db_ID
      and i.db_ID = d.db_ID
      and i.HOST_ID = h.host_id
      and upper(H.HOST_NAME) = v_hostname
      and upper(D.DB_NAME) = v_instance
      and upper(Ac.ACCOUNT_NAME) = v_schema;
      --APPEND DB_ID TO THE SYNOYNM NAME
      v_synonym := 'CUSTOMER_'||v_db_id;
      FOR cust_rec IN insert_customer
      LOOP
         INSERT INTO CUSTOMER_RESULTS (First_Name, Last_Name)
         VALUES (cust_rec.customer_fname, cust_rec.customer_lname);
      END LOOP;
      COMMIT;
    END;
    Rgs,
    Rob

    Hi
    rules engine style with table that holds the logic or code SQL directly in the procedure and IF THEN ELSE with db_id. Latter is better because SQL is native and objects are checked every time procedure is compiled.
    James showed the simplest way but this rather complex way gives you more flexibility between instances if ever needed.
    CREATE TABLE synonym_dml(db_id number not null primary key, sql_text clob)
    INSERT INTO synonym_dml VALUES (100, 'INSERT INTO customer_results (first_name, last_name) SELECT customer_fname,customer_lname FROM customer100')
    INSERT INTO synonym_dml VALUES (200, 'INSERT INTO customer_results (first_name, last_name) SELECT customer_fname,customer_lname FROM customer200')
    set serveroutput on size unlimited
    create or replace
    PROCEDURE Execute_Synonym_Dml(p_host VARCHAR2, p_db_name VARCHAR2, p_schema VARCHAR) IS
    BEGIN
      FOR r IN (
        SELECT sql_text FROM synonym_dml
        --  WHERE db_id IN (
        --    SELECT d.db_id
        --    FROM t_mv_db_accounts ac, t_mv_db_instances i, t_mv_dbs d, t_mv_hosts h
        --    WHERE ac.db_id = d.db_id
        --      AND i.db_id = d.db_id
        --      AND i.host_id = h.host_id
        --      AND upper(h.host_name)      = p_hostname
        --      AND upper(d.db_name)        = p_instance
        --      AND upper(ac.account_name)  = p_schema
      LOOP
        DBMS_OUTPUT.PUT_LINE('-- executing immediately ' || r.sql_text);
        --EXECUTE IMMEDIATE r.sql_text;
      END LOOP;
    END;
    create or replace
    PROCEDURE Execute_Synonym_Dml_Too(p_host VARCHAR2, p_db_name VARCHAR2, p_schema VARCHAR) IS
      PROCEDURE DB_ID_100 IS
      BEGIN
        DBMS_OUTPUT.PUT_LINE('-- executing DB_ID_100');
        --INSERT INTO customer_results (first_name, last_name) SELECT customer_fname,customer_lname FROM customer100;
      END;
      PROCEDURE DB_ID_200 IS
      BEGIN
        DBMS_OUTPUT.PUT_LINE('-- executing DB_ID_200');
        --INSERT INTO customer_results (first_name, last_name) SELECT customer_fname,customer_lname FROM customer200;
      END;
    BEGIN
      FOR r IN (
        SELECT 100 db_id FROM dual
        --  SELECT d.db_id
        --  FROM t_mv_db_accounts ac, t_mv_db_instances i, t_mv_dbs d, t_mv_hosts h
        --  WHERE ac.db_id = d.db_id
        --    AND i.db_id = d.db_id
        --    AND i.host_id = h.host_id
        --    AND upper(h.host_name)      = p_hostname
        --    AND upper(d.db_name)        = p_instance
        --    AND upper(ac.account_name)  = p_schema
      LOOP
        IF (r.db_id = 100) THEN
          DB_ID_100;
        ELSIF (r.db_id = 200) THEN
          DB_ID_200;
        ELSE
          RAISE_APPLICATION_ERROR(-20001, 'Unknown DB_ID ' || r.db_id);
        END IF;
      END LOOP;
    END;
    EXECUTE Execute_Synonym_Dml('demo','demo','demo');
    EXECUTE Execute_Synonym_Dml_Too('demo','demo','demo');
    DROP TABLE synonym_dml PURGE
    DROP PROCEDURE Execute_Synonym_Dml
    table SYNONYM_DML created.
    1 rows inserted.
    1 rows inserted.
    PROCEDURE EXECUTE_SYNONYM_DML compiled
    PROCEDURE EXECUTE_SYNONYM_DML_TOO compiled
    anonymous block completed
    -- executing immediately INSERT INTO customer_results (first_name, last_name) SELECT customer_fname,customer_lname FROM customer100
    -- executing immediately INSERT INTO customer_results (first_name, last_name) SELECT customer_fname,customer_lname FROM customer200
    anonymous block completed
    -- executing DB_ID_100
    table SYNONYM_DML dropped.
    procedure EXECUTE_SYNONYM_DML dropped.

  • Use Of Numeric Table Names For Performance

    Just a question if anyone has any experience using numeric table names(ie... 100, 200, 300... etc) instead of the typical naming conventions (ie... data_user_statistics, statsUser etc....) in their databases.
    I had a database admin advise me that by using the short numerical names, you could potentially see a measurable gain in performance. Not sure how much that would be on a smaller 30-50 table database. I would think however, that if the database is heavily utilized, that you would see some performance gains. Just curious if anyone had any thoughts on this.

    user10887160 wrote:
    Just a question if anyone has any experience using numeric table names(ie... 100, 200, 300... etc) instead of the typical naming conventions (ie... data_user_statistics, statsUser etc....) in their databases.
    I had a database admin advise me that by using the short numerical names, you could potentially see a measurable gain in performance. Not sure how much that would be on a smaller 30-50 table database. I would think however, that if the database is heavily utilized, that you would see some performance gains. Just curious if anyone had any thoughts on this.Does your admin suggest the same for columns ?
    Imagine having to work out the (otherwise obvious) error in something like:
    select
            "100"."302",
            "200"."707"
    from
            "100",
            "200"
    where
            "100"."305" = 104395
    and     "200"."709"="100"."303"
    ;(And I have seen it in a production system - except the tables started with a "T" and the columns with a "C" - and it was a complete pain in the backside to do performance trouble-shooting.)
    Regards
    Jonathan Lewis
    http://jonathanlewis.wordpress.com
    http://www.jlcomp.demon.co.uk
    To post code, statspack/AWR report, execution plans or trace files, start and end the section with the tag {noformat}{noformat} (lowercase, curly brackets, no spaces) so that the text appears in fixed format.
    "Science is more than a body of knowledge; it is a way of thinking"
    Carl Sagan                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Create Dynamic table name in the select statement.

    I use oracle reports 6i to make myrep.rdf , this report created using certain select query Q1, I created a formula column in this report,
    in the formula column  I write pl/sql block statements to select the data from certain table depends on the output of a column in Q1,
    I want to make the pl/sql block dynamically enough to change the user which I select the data from depends on the connected user
    Ex: if I connected with user = 'KAM14'
    the pl/sql block will be
    select x into v_value from kam13.bil_file where .....;
    and if  I connected with user = 'KAM13'
    the pl/sql block will be
    select x into v_value from kam12.bil_file where .....;
    and so on
    how can I do this in the pl/sql block ...
    Thanks in Advance.

    I am not sure I understood properly, but I think you should create bil_file table under a different user and create synonyms  under KAM1x users.
    Regards

  • How to use CheckBox in Table to do mulit-selection in Creator2 Update1?

    Hi.
    I put CheckBox(checkbox1) into Table to do a multi-selection effect..
    and I set checkbox1's selected to true to make default selection.
    however checkbox1 doesn't show selected in at Design Time in Creator2 , and also at Runtime in Firefox.
    then I put another CheckBox(checkbox2) outside the Table, and set selected to ture.
    chekcbox2 is default selected both in Designtime and Runtime.
    I am confused about that
    And, more troubles is, I can't know which Row datas were checked.
    I call CheckBox.getSelected(checkbox1.getID()) got NULL.
    I call checkbox1.getSelected() got NULL.
    Then I write a TableDataProvider to handle this Table and always return Boolean.TRUE at selection field
    But still no work.
    Does anyone know how to do multi-selection in Table?
    Thanks a lot.

    Hi,
    I also test RadioBox in Table and set RadioBox named 'rbSelection' , the table is bind to a dataprovider.
    But, It does't work, too.
    I can't get the selection from any API I know in a Button action (outside of Table)
    RadioButton.getSelected(rbSelection.getName())) return null
    rbSelection.getSelectedValue() return true
    rbSelection.getSelected()) return null
    rbSelection.getSubmittedValue()) return null
    tableRowGroup1.getSelectedRowKeys().length size is 0
    But when I use ((HttpServletRequest)this.getFacesContext().getExternalContext().getRequest()).getParameter("rbSelection")
    I can get the correct selection result.
    Is this a Creator2 bug or my mistake?
    THANKS~

  • Using "FIND IN TABLE" to search in selected columns

    Hi,
    I want to use "FIND" to search for a pattern in certain table columns only, but ABAP Keyword Documentation ([FIND IN TABLE itab|http://help.sap.com/abapdocu_70/en/ABAPFIND_ITAB.htm]) does not state about this option.
    Is it possible to do so?
    Thanks,
    Joon Meng

    Hi,
    1. if you want to find particular record u can use 
    READ TABLE itab { table_key  | free_key | index } result.
    2. if you want to compare the fied value level u can use
    log_exp - Logical Expressions
    CO, CN, CA, NA, CS, NS, CP, NP
    Regards,
    G

  • How do I use Derived Table to dynamically choose fact table

    How do I use the Derived Table functionality to dynamically choose a fact table?
    I am using BO XI R2 querying against Genesys Datamart kept in Oracle 10g.  The datamart contains aggregated fact tables at different levels (no_agg, hour, day, week, etc...) I would like to build my universe so that if the end user chooses a parameter to view reports at daily granularity, then the daily fact table is used;  choose hourly granularity, then hourly fact table is used, etc....
    I tried using dynamic SQL in Oracle Syntax, but Business Obljects Universe didn't like that type of coding.
    The tables look something like this:
    O_LOB1_NO_AGG o
    inner join V_LOB1_NO_AGG v on o.object_id = v.object_id
    inner join T_LOB1_NO_AGG t on v.timekey = t.timekey
    Likewise, in the 'hour', 'day', 'week', etc... fact tables, the Primary Key to Foreign Key names and relationships are the same.  And the columns in each O_, V_, T_ fact table is the same, or very similar (just aggregated at different levels of time).
    I was thinking of going a different route and using aggregate aware; but there are many Lines of Business (20+) and multiple time dimensions (7) and I believe aggregate aware would require me to place all relevant tables in the Universe as separate objects, which would create a large Universe with multiple table objects,  and not be maintenance-friendly. I also was going to dynamically choose Line of Business (LOB) in the derived tables, based on the end user choosing a parameter for LOB, but that is out-of-scope for my current question.  But that information sort of points you down the train of thought I am travelling. Thanks for any help you can provide!

    You can create a derived table containing a union like the following:
    select a,b,c from DailyFacts where (@prompt('View'....) = 'Daily' and (<rest of your where conditions here if necessary>)
    union
    (select a,b,c from MonthlyFacts where (@prompt('View'....) = 'Monthly' and (<rest of your where conditions here if necessary>))
    union
    (select a,b,c from YearlyFacts where (@prompt('View'....) = 'Yearly' and (<rest of your where conditions here if necessary>))
    I assume that you are familiar with the @prompt syntax
    Regards,
    Stratos

  • Using Table name in Read statement dynamically

    Hi Experts,
    I have the following requirement.
    Based on a country code say "A" , "B", "C" and based on this i have to read different internal tables lt_tabA, lt_tabB and lt_tabC.
    The table key can be given dynamically, but how can i use the internal table name dynamically without using if statements.
    Please help.
    Thanks!
    Best Regards,
    Gayathri

    Hi Gayathri,
    something like
    DATA:
        lt_t100 TYPE TABLE OF t100,
        lt_t000 TYPE TABLE OF t000.
      FIELD-SYMBOLS:
        <table> TYPE table,
        <rec>   TYPE ANY,
        <field> TYPE ANY.
      SELECT:
        * INTO CORRESPONDING FIELDS OF TABLE lt_t100 FROM t100 UP TO 10 ROWS,
        * INTO CORRESPONDING FIELDS OF TABLE lt_t000 FROM t000 UP TO 10 ROWS.
      CASE abap_true.
        WHEN space.
          ASSIGN  lt_t100 TO <table>.
        WHEN OTHERS.
          ASSIGN  lt_t000 TO <table>.
      ENDCASE.
      READ TABLE <table> with key ('MANDT') = sy-mandt ASSIGNING <rec>.
    Regards,
    Clemens

Maybe you are looking for