Results 1 to 5 of 5
  1. #1
    Join Date
    Aug 2003
    Posts
    8

    Unanswered: dynamic table name in sql query

    Hi,

    I have a table ABC which has a column A_table. This column contains various table_names depending on A_id.

    I am trying to write a procedure to get
    select <column_name> from A_table . Is there any way in whichc this can be done.
    Note: here column_name is also a variable
    and A_table is a column in ABC.

    For example if I want to find the values in column Z of a table corresponding to A_id = 1
    I have to get the corresponding table name for A_id from table ABC.. (say it is table _1).
    then the query will be : select z from table_1;

    Can someone please help me with this.
    Regards,
    SD

  2. #2
    Join Date
    Sep 2002
    Location
    UK
    Posts
    5,171
    Provided Answers: 1

    Re: dynamic table name in sql query

    Originally posted by sd_100
    Hi,

    I have a table ABC which has a column A_table. This column contains various table_names depending on A_id.

    I am trying to write a procedure to get
    select <column_name> from A_table . Is there any way in whichc this can be done.
    Note: here column_name is also a variable
    and A_table is a column in ABC.

    For example if I want to find the values in column Z of a table corresponding to A_id = 1
    I have to get the corresponding table name for A_id from table ABC.. (say it is table _1).
    then the query will be : select z from table_1;

    Can someone please help me with this.
    Regards,
    SD
    The keyword is "dynamic" - you need to use dynamic SQL like this for a single-row select:

    EXECUTE IMMEDIATE 'SELECT ' || v_column_name || ' FROM ' || v_table_name || ' WHERE ...' INTO v_value;

    or for a multi-row select:

    DECLARE
    rc SYS_REFCURSOR;
    BEGIN
    OPEN rc FOR 'SELECT ' || v_column_name || ' FROM ' || v_table_name || ' WHERE ...';
    LOOP
    FETCH rc INTO ...;
    EXIT WHEN rc%NOTFOUND;
    END LOOP;
    END;

  3. #3
    Join Date
    Aug 2003
    Posts
    8
    Tony,

    Thanks Again..
    Looks like its working. But here I am facing yet another problem :-((.
    The query is taking a long time..
    Does fetch make it complicated.

    SD

  4. #4
    Join Date
    Sep 2002
    Location
    UK
    Posts
    5,171
    Provided Answers: 1
    Originally posted by sd_100
    Tony,

    Thanks Again..
    Looks like its working. But here I am facing yet another problem :-((.
    The query is taking a long time..
    Does fetch make it complicated.

    SD
    Please post your code so we can see if there's a problem.

  5. #5
    Join Date
    Aug 2003
    Posts
    8
    Tony,

    I resolved the problem..
    thanks for all your help.

    SD

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •