Selecting a query as a table name

Greedings,
an example to explain what im trying to do
lets says
query1:=table1.name||'_code';
so outcome will be for example 'citizen_code'
what im trying to do is select the specific query to get the required data
select * from query1@seconddatabase where .....
is it possible to do something like that?
thanks for your time,
dem

The common ways to do this are use dynamic SQL or synonym frigging (which I would massively discourage).
A nice work around is to do somwething like this...
CREATE OR REPLACE VIEW emp_vw
AS
SELECT 'DB1' db,
       empno
FROM   emp@db1
UNION ALL
SELECT 'DB2' db,
       empno
FROM   emp@db2;
SELECT *
FROM   emp_vw
WHERE  db = 'DB2';Keep it in the SQL!
Cheers
Ben

Similar Messages

  • Using sql query as a table name

    hello,
    I have a table(say table1) which is storing the names of some other tables. I want to access the name of a table from table1 using sql query and then use the result of this query as the table name to access the data from
    retrieved table name. How can I do this ?
    ex:
    select * from (select tablename from table1 where tableid='1');
    I want to do something likw this. How can I do this?

    I want to access the name of a table from table1 using sql query and then use the result of this query as the table name to access the data from retrieved table name. How can I do this ?e.g. like this:
    SQL> with table1 as (
    select 'emp' tablename from dual
    select extractvalue(x.column_value, 'ROW/ENAME') ename
    from table1, xmltable('ROWSET/ROW' passing dbms_xmlgen.getxmltype('select * from ' || tablename)) x
    ENAME                                                                                                                       
    SMITH                                                                                                                       
    ALLEN                                                                                                                       
    WARD                                                                                                                        
    JONES                                                                                                                       
    MARTIN                                                                                                                      
    BLAKE                                                                                                                       
    CLARK                                                                                                                       
    SCOTT                                                                                                                       
    KING                                                                                                                        
    TURNER                                                                                                                      
    ADAMS                                                                                                                       
    JAMES                                                                                                                       
    FORD                                                                                                                        
    MILLER                                                                                                                      
    14 rows selected.

  • Select query to get table names

    Hi,
    Can i retrieve a table name from a select query if i know value of one of the columns in the table?
    Glen

    Can't you take a look at the source code and see what table those values are coming from? That's likely the easiest solution.
    Barring that, you could use dynamic SQL, but it's going to be awfully inefficient. Something like
    FOR x IN (SELECT * FROM user_tab_cols WHERE data_type = 'VARCHAR2')
    LOOP
      EXECUTE IMMEDIATE
        'SELECT COUNT(*) FROM ' || x.table_name ||
        ' WHERE ' || x.column_name || ' = <<literal value>>'
        INTO l_cnt;
      IF( l_cnt > 1 )
      THEN
        DBMS_OUTPUT.PUT_LINE( 'Found the value' );
      END IF;
    END LOOP;This assumes that you know at least what data type the value is stored in. It's also going to generate a tremendous number of full table scans, so it'll be slow as molasses on a system of any size.
    Justin

  • Query for retreiving table names that have the same data

    Hi,
    Does anybody know how to retreive all the table names that have the same data in their respective tables but i dont know the table names or its fields. Is there any possible query to perform this action???
    Thanks in Advance,
    Balaji.

    What about...
    WITH manager_list AS
    SELECT name,
            LTRIM(MAX(SYS_CONNECT_BY_PATH(id,','))
            KEEP (DENSE_RANK LAST ORDER BY curr),',') AS employees
    FROM   (SELECT m.name,
                    e.id,
                    ROW_NUMBER() OVER (PARTITION BY m.name ORDER BY e.id) AS curr,
                    ROW_NUMBER() OVER (PARTITION BY m.name ORDER BY e.id) -1 AS prev
             FROM   manager m,
                    join_table jt,
                    employee e
      WHERE m.id           = jt.manager_id
      AND   jt.employee_id = e.id
      AND   m.name = :P_MANAGER)
      GROUP BY name
      CONNECT BY prev = PRIOR curr AND name = PRIOR name
      START WITH curr = 1
    ), all_list AS
    SELECT name,
            LTRIM(MAX(SYS_CONNECT_BY_PATH(id,','))
            KEEP (DENSE_RANK LAST ORDER BY curr),',') AS employees
    FROM   (SELECT m.name,
                    e.id,
                    ROW_NUMBER() OVER (PARTITION BY m.name ORDER BY e.id) AS curr,
                    ROW_NUMBER() OVER (PARTITION BY m.name ORDER BY e.id) -1 AS prev
             FROM   manager m,
                    join_table jt,
                    employee e
      WHERE m.id           = jt.manager_id
      AND   jt.employee_id = e.id)
      GROUP BY name
      CONNECT BY prev = PRIOR curr AND name = PRIOR name
      START WITH curr = 1
    SELECT a.*
    FROM   manager_list m,
           all_list a
    WHERE  m.employees = a.employeesWould be easier in 11g, but I don't have an installation here so this is based on 10g.
    Cheers
    Ben

  • Bex Query: Too many table names in the query The maximum allowable is 256

    Hi Experts,
    I need your help, Im working on a Query using a multiprovider of 2 datastores, I need to work with cells to assign specific acconts values to specific rows and columns, so I was creating a Structure with elements from a Hierarchy, but I get this error when I'm half way of the structure:
    "Too many table names in the query. The maximum allowable is 256.Incorrect syntax near ')'.Incorrect syntax near 'O1'."
    Any idea what is happening? is ti possible to fix it? do I need to ask for a modification of my Infoproviders? Some one told me is possible to combine 2 querys, is it true?
    Thanks a lot for your time and pacience.

    Hi,
    The maximum allowable limit is 256 holds true. It is the max no. of characteristics and key figures that can be used in the column side. While creating a structure, you create key figures (restricted or calculated) and formulas etc.. The objects that you use to create these should not be more than 256.
    http://help.sap.com/saphelp_nw70/helpdata/EN/4d/e2bebb41da1d42917100471b364efa/frameset.htm
    Not sure if combination of 2 query's is possible.  You can use RRI. Or have a woorkbook with 2 queries.
    Hope it helps.

  • Select data from all the table names in the view

    Hi,
    "I have some tables with names T_SRI_MMYYYY in my database.
    I created a view ,Say "Summary_View" for all the table names
    with "T_SRI_%".
    Now i want to select data from all the tables in the view
    Summary_View.
    How can i do that ? Please throw some light on the same?
    Thanks and Regards
    Srinivas Chebolu

    Srinivas,
    There are a couple of things that I am unsure of here.
    Firstly, does your view definition say something like ...
    Select ...
    From "T_SRI_%"
    If so, it is not valid. Oracle won't allow this.
    The second thing is that your naming convention for the
    tables suggests to me that each table is the same except
    that they store data for different time periods. This would be
    a very bad design methodology. You should have a single
    table with an extra column to state what period is referred to,
    although you can partition it into segments for each period if
    appropriate.
    Apologies if i am misinterpreting your question, but perhaps
    you could post your view definition and table definitions
    here.

  • SQL query to see table names for specific columns

    hi
    i have a database containing more than 100 tables. I want to see all the tables containg a column 'Employee_id'. plz tell me SQL query some other way.
    Thanks

    Time to learn data dictionary basics
    SELECT DISTINCT table_name
    FROM all_tab_cols
    WHERE column_name ='EMPLOYEE_ID';

  • Running a query in which table name and column name are passed as arguments

    Hello,
    I have a pl/sql code in which table_name and column_name are defined as variables.
    I want to run a sql query like update table_name set column_name = <value> where id='xyz';
    How can I achieve this?
    Thanks in advance.
    Regards.

    GHD wrote:
    DECLARE
    v_table_name VARCHAR2(50) := 'employees';
    v_column_name VARCHAR2(50) := 'first_name';
    V_SQL         VARCHAR2(1000);
    BEGIN
    V_SQL := 'UPDATE '||v_table_name||' SET '||v_column_name||'= ''Ray'''||'WHERE EMPLOYEE_ID = 101';
    EXECUTE IMMEDIATE v_sql;
    END;Hope it will be helpful.Yes quite. (and the following applies to ALL responses thus far)
    It helps in reducing performance.
    It helps in fragmenting the shared pool.
    It helps in causing ORA-04031 unable to allocate %s bytes of shared memory errors.
    It is a brilliant example... OF HOW NOT TO WRITE ORACLE CODE.

  • Query to find relevant Table name

    Hi i need a SQL query which should return me relevant table names. i.e. if there is table 'EMP' , then query should give table names with below result:
    EMP
    EMP_1
    EMP_2
    EMP_3
    EMP_4
    i.e. All tables which is starting with EMP (No Hardcoding of table, It should be dynamic way).I know we can achieve through SELECT * FROM USER_OBJECTS WHERE OBJECT_NAME LIKE 'EMP%'.
    But here object_name i will passing dynamically.
    Actually my main purpose is to create backup tables i.e. EMP is main table and EMP_1,EMP_2,EMP_3 .. EMP_100 is backup table.Now whenever i am making the any changes in EMP table, then i should take the backup of exiting EMP table and backup data should go to EMP_101 (as last table with sequence is EMP_100).
    Any idea in SQL , PL/SQL i would appreciate .
    Thanks

    here is a way:
    set serveroutput on
    declare
    tab_name varchar2(30) := 'EMP';
    new_tab_name varchar2(30);
    begin
      for i in (
            select * from (
                select t.*,
                        row_number() over(order by t.table_name desc) as row_nr ,
                        min(table_name) over () as originiall_table
                        from all_tables t
                where table_name like tab_name||'%'
            ) where row_nr = 1
      ) loop
        new_tab_name := substr(i.table_name, 1, instr(i.table_name, '_') - 1 )
                        ||'_'
                        || (TO_NUMBER(substr(i.table_name, instr(i.table_name, '_') + 1 )) + 1 ) ;
        execute immediate 'create table '||new_tab_name||' as select * from '||i.originiall_table;   
      end loop;
    end;but why do you want to keep too many copies of tables in db?
    anytime you will get problems with tablespaces.

  • SQL query with From table being entered in twice

    I have a query that is doing an exist clause with the inner select statement querying the T_PROJECTS table using two different alias "t3 & t2".
    SELECT t0.ID, t0.EFFECTIVEDATE, t0.CUSTOMERID, t0.PROJECTID, .... FROM T_FINANCIALDATAS t0 WHERE ((t0.PROJECTID = 2271) AND (EXISTS (SELECT t1.TMPUSERID FROM T_PROJECTS t3, T_PROJECTS t2 , T_PROJECTSUSERS t1 WHERE (((( t2.CUSTOMERID = 1) AND (t1.USERID = 2276)) AND (t1.PROJECTID = t3.ID )) AND ( t2.ID = t1.PROJECTID))) AND (t0.CUSTOMERID = 1)))
    They need to be combined so I'm using only one table alias. They way the query get's built is a little complicated. The Exist clause get's built as a ReportQuery and then that get's passed into another method which eventually is added to a top level Expression as such:
    ReportQuery existsQuery = new ReportQuery(existsClass, existsExpressionHolder.getExpression());
    expHolder.addAnd(expHolder.getExpressionBuilder().exists(existsQuery));
    Question: what causes the double table alias from showing up? From what I read it seems like it's caused when you use two different ExpressionBuilders?

    Could you include the code that builds the Expression.
    Perhaps try to reproduce the issue in a simple isolated example. Generally every ExpressionBuilder used in a query represents a table/alias.
    What version of TopLink are you using?
    The duplicate alias seems repetitive, but doesn't seem like it will have any effect on the query result, other than its efficiency.
    James : http://www.eclipselink.org

  • How to pass dynamically table name in my cursor declaration

    Hi:
    I am new. could you please let me know how to pass a table name dynamically in my cursor declaration? for instance I am declaring the following cursor in my pl/sql procedure:
    CURSOR crs_validate IS
    select * FROM <ACT_JUN_2006_LOB>;
    this ACT_JUN_2006_LOB table name, I should able to pass it when I open the cursor ... any help appreciated. thanks.
    srini

    Thanks all for the response. REFCURSOR does work: here is an example ... which I found on-line
    procedure emp_test(
    month varchar2,
    year varchar2)
    is
    type cur_typ is ref cursor;
    c cur_typ;
    query_str varchar2(200);
    emp_number number := 7900;
    salary number;
    name varchar2(30);
    Begin
    query_str := 'Select empno, ename, sal from emp_' || month ||'_'||year
    || ' where empno = :id';
    open c for query_str using emp_number;
    loop
    fetch c into emp_number, name, salary;
    exit when c%notfound;
    dbms_output.put_line(emp_number);
    end loop;
    close c;
    end;

  • Read table, table name in variable

    Hi all,
    I am try trying to do the following.
    Select statement to get the table name --> store in tname (variable).
    Now, I have to do a select to read the data in this table (table name is in tname variable) based on some conditions
    How do I do this?
    1st step
         Select ME_TECH from RSAC into tname
            where NAME = 'PLANT'
                  and DATEFROM <= ldate
                  and DATETO >= ldate.
    2nd step??
    Thanks,
    Anirudh.

    report ztest.
    parameters: p_table type dd02l-tabname.
    field-symbols: <fs> type standard table." of (p_table).
    select * from (p_table)
    into table <fs>
    up to 20 rows.
    There is another way using CL_ALV_TABLE_CREATE, for this you have to pass the fieldcatalog.
    it return the internal table reference. using that you can proceed.

  • Dynamic Select query is failing with error "Invalid Table Name"

    OPEN rc FOR 'SELECT count(*) from :s' USING tab_name;
    fetch rc into rec_count;
    CLOSE rc;
    my requirement is to build dynamic select query to retrieve the total count of rows in each table ( variable tab_name contains the table_name )
    But I am getting stuck by this errror, not sure if there is any alternative !
    ORA-00903: invalid table name
    ORA-06512: at line 43

    OPEN rc FOR 'SELECT count(*) from '||tab_name;
    fetch rc into rec_count;
    CLOSE rc;
    -- This will work
    1. Create a sql statement.
    2. Open ref cursor for that statement.

  • How to assign table name for select query in loop.

    Hi friends my requirement is count the no of records of all the database table which comes into an internal table ."Check the below coding". Iam  fetching the tables from dd03l table into an internal table .plz give me a sujjesion how to assign a table name in select query  in a loop.
      SELECT tabname FROM dd09l
                INTO TABLE i_dd09l
                WHERE protokoll = 'X'.
      IF sy-subrc = 0.
        SORT i_dd09l BY tabname.
      ENDIF.
      LOOP AT i_dd09l.
        SELECT COUNT(*) INTO val FROM i_dd09l-tabname.
        IF sy-subrc = 0.
          i_dd09l-count = val.
        ENDIF.
        MODIFY i_dd09l INDEX sy-index.
        CLEAR val.
      ENDLOOP.
    error : 'I_DD09L-TABNAME' is not defined in the abap dictionary as a table.

    data: dy_table type ref to data,
          dy_line type ref to data,
          xfc type lvc_s_fcat,
          ifc type lvc_t_fcat,
          dy_field type ref to data.
    LOOP AT i_dd09l.
    perform get_structure using i_dd09l-tabname .
    CREATE DATA dy_table TYPE TABLE OF (_dd09l-tab_name).
        UNASSIGN <dyn_table>.
        ASSIGN dy_table->* TO <dyn_table>.
    SELECT COUNT(*) INTO val FROM <dyn_table>.
    IF sy-subrc = 0.
    i_dd09l-count = val.
    ENDIF.
    MODIFY i_dd09l INDEX sy-index.
    CLEAR val.
    ENDLOOP.
    form get_structure using p_table.
      data : idetails type abap_compdescr_tab,
      xdetails type abap_compdescr.
      data : ref_table_des type ref to cl_abap_structdescr.
    Get the structure of the table.
      ref_table_des ?=
      cl_abap_typedescr=>describe_by_name( p_table ).
      idetails = ref_table_des->components.
      loop at idetails into xdetails.
        clear xfc.
        xfc-fieldname = xdetails-name .
        xfc-datatype = xdetails-type_kind.
        xfc-inttype = xdetails-type_kind.
        xfc-intlen = xdetails-length.
        xfc-decimals = xdetails-decimals.
        append xfc to ifc.
      endloop.
    endform.                    "get_structure
    Try like this hope it will work.
    Regards,
    madan.

  • How to find table name(s) in a dynamic query

    In one of our (9iAS PORTAL)applications, any user can able to run their query statment and get output. All queries will be executed as dynamic SQL thru' a common shema/user who has 'SELECT' privilege on all tables but all users don't have this privilege on all tables. Now, before executing any query I need to find out what are the table name(s) used in this query to check the privilege for the respective user. How do I extract all table names being used in a dynamic query?.
    Thanks
    -Krishnamurthy

    I guess that his users log in to application first, then application uses one account to log in to database, so application are not direct database user since all users share the same account to database. If so, when a user lgins in, you may write it down from application to a database audit table, and you need to write down the dynamic query to the database audit table too, then you may query that audit table to find out. up to here, it looks that your application has to do more to assign what role to a user running the application, since database does not know what user is assessing it.

Maybe you are looking for