Passing table names through variables

Hi All,
Is it possible to pass the table name in a query using a variable.
For example - can we perform a select on a table where the table name is passed using a variable.
Pl assist. Thanks.

Hello,
Are you wanting to do this in a procedure? Say the table name being passed in as Input Parameter?
We can do that using Dynamic SQL:
CREATE PROCEDURE "PROC_01"
(IN v_IN_Var1 NVARCHAR)
LANGUAGE SQLSCRIPT AS
BEGIN
    DECLARE ABC NVARCHAR(300) := NULL;
    ABC := 'SELECT * FROM ' || :v_IN_Var1;
    EXEC (:ABC);
END;
CALL PROC_01 ('DUMMY');
But the only thing is you'll not be able to see the result set directly.
You might wan2 fire the select to insert the data into a different table.

Similar Messages

  • Passing Table Name to Stored Procedure for From Clause

    Is it possible to pass a table name to a stored procedure to be used in the From clause? I have the same task to perform with numerous tables and I'd like to use the same SP and just pass the table name in. Something like this:
    =======================================
    CREATE OR REPLACE PROCEDURE SP_TEST(
    in_TABLE IN VARCHAR2,
    AS
    V_TABLE VARCHAR2(10);
    BEGIN
    V_TABLE := 'st_' || in_TABLE; -- in_TABLE is 2-3 character string
    SELECT some_columns
    INTO some_variables
    FROM V_TABLE
    WHERE some_conditions...;
    END;
    =======================================
    I'm also using the passed table name to assign to variables in the Select and Where clauses. What I'm getting is an error that V_TABLE must be declared. When I hard code the table name, I don't get any errors, even though I'm also using the same method to assign values in the Select and Where clauses.
    Thanks,
    Ed Holloman

    You need to use dynamic SQL whenever you are swapping out object names (tables, columns).
    create or replace procedure sp_test
      (in_table in varchar2)
    is
      -- variables
    begin
      execute immediate 'select a, b, c from st_' || in_table || ' where x = :xval and y = :yval'
         into v_a, v_b, v_c using v_x, v_y;
    end;

  • Passing TABLE NAME as parameter is possible or not?

    I want develop a small/simple report like this
    TABLE NAME :
    WHERE :
    ORDER BY :
    QUERY ROWS
    In the above model i want to pass all the three (TABLE NAME,WHERE and ORDER BY) as a parameter.
    My doubt, is that possible to pass TABLE NAME as a parameter? If so!
    When i enter any TABLE NAME it has to fetch me out the records of that table (Based on WHERE condition and ORDER BY).
    Is that possible to do?
    Need some help!
    Edited by: Muthukumar Seshadri on Aug 10, 2012 6:19 PM

    Yes, it is possible with lexical parameters. Look in the help for examples:
    SELECT Clause
    SELECT &P_ENAME NAME, &P_EMPNO ENO, &P_JOB ROLE  FROM EMP
    P_ENAME, P_EMPNO, and P_JOB can be used to change the columns selected at runtime.  For example, you could enter DEPTNO as the value for P_EMPNO on the Runtime Parameter Form. 
    Note that in this case, you should use aliases for your columns.  Otherwise, if you change the columns selected at runtime, the column names in the SELECT list will not match the Report Builder columns and the report will not run.
    FROM Clause
    SELECT ORDID, TOTAL FROM &ATABLE
    ATABLE can be used to change the table from which columns are selected at runtime.  For example, you could enter ORD for ATABLE at runtime. 
    If you dynamically change the table name in this way, you may also want to use lexical references for the SELECT clause (look at the previous example) in case the column names differ between tables.
    WHERE Clause
    SELECT ORDID, TOTAL FROM ORD WHERE &CUST
    ORDER BY Clause
    SELECT ORDID, SHIPDATE, ORDERDATE, TOTAL  FROM ORD ORDER BY &SORT You have to be really careful with this approach. Dynamic SQL may cause serious performance problems.
    Edited by: InoL on Aug 10, 2012 10:06 AM

  • Pass table name as a parameter to function

    Is there a way to pass table name as a parameter to functions? Then update the table in the function.
    Thanks a lot.
    Jiaxin

    Hi, Harm,
    Thank you very much for your suggestion and example. But to get my program work, i need to realise code like follows:
    CREATE OR REPLACE FUNCTION delstu_func(stuno char) RETURN NUMBER AS
    BEGIN
    EXECUTE IMMEDIATE 'DELETE FROM student s' ||
    'WHERE' || 's.student_number' || '=' || stuno;
    LOOP
    DBMS_OUTPUT.PUT_LINE('record deleted');
    END LOOP;
    END;
    SELECT delstu_func('s11') FROM STUDENT;
    The intention is to check if such a function can perform operations such as update, delete and insert on occurence of certain values. When executing the above statement, the system returns an error message:
    ERROR at line 1:
    ORA-00933: SQL command not properly ended
    ORA-06512: at "SCMJD1.DELSTU_FUNC", line 3
    Could you tell me where is wrong?
    Jiaxin

  • Pass table name as parameter in prepared Statement

    Can I pass table name as parameter in prepared Statement
    for example
    select * from ? where name =?
    when i use setString method for passing parameters this method append single colon before and after of this parameter but table name should be send with out colon as SQL Spec.
    I have another way to make sql query in programing but i have a case where i have limitation of that thing so please tell me is it possible with prepared Statment SetXXx methods or not ?
    Thanks
    Haroon Idrees.

    haroonob wrote:
    I know ? is use for data only my question is this way to pass table name as parameterI assume you mean "how can I do it?" As I have already answered "is this the way?" with no.
    Well, I would say (ugly as it is) String concatenation, or stored procedures.

  • How to pass attribute values through variables in JSP  Custom TagLib

    Hi,
    Can anybody help me how to pass values through varuables in the jsp custom tag.
    i am using JSP custom tag. I am unable to pass attribute values through variables.
    <invitation:invdetails invid="<%=invid%>"/> The value is passing as <%=invid%> ,not value of the invid.
    But i am getting throuh the fllowing
    <invitation:invdetails invid='1' />
    Please anybody suggest me how to pass value by using the variable.

    Hi,
    It sounds like you need to set the <rtexprvalue> tag to true in the TLD for your tag. If you do this the tag will read in the value you are trying to pass to it.
    dapanther...

  • JSP sql - set table name in variable

    I'm trying to set my table name in variable, what is the syntax in sql of selecting from a table which name is set with a variable name?

    That's easy :
    Say, ur table name is MY_TABLE.
    Now, set a variable say x as :
    var x = "MY_TABLE"; (Javascript)
    or
    String x = "MY_TABLE" (JSP/Servlet);
    Finally, use the SQL as,
    String SQL = "SELECT * FROM " + x + "WHERE condition". (JSP/Servlet).
    or
    var SQL = "SELECT * FROM " + x + "WHERE condition". (Javascript).
    and BINGO !!
    Do keep me posted.
    Cheers !!
    Sherbir

  • Passing table name to a procedure and then need to open a cursor ..

    Hi All,
    I have been out of touch in plsql for sometime and need to do something like :
    passing table name to a procedure while calling(fp_table_old captures this value) and then need to open a cursor for this table in 'for i in (select * from fp_table_old )', one of the ways I tried is : for i in (execute immediate Lv_sql_query ) but its not working for me, please find the code below for reference, I know I am sounding stupid but I have been very out of touch, please help.
    code :
    create procedure p_table_compare(fp_table_old in varchar2, fp_table_new in varchar2)
    as
    Lv_sql_query varchar2(2000);
    begin
         Lv_sql_query := 'select * from '||fp_table_old;
         for i in (Lv_sql_query)
         loop
              dbms_output.put_line(i.employee_id);
         end loop;
    end;
    Regards
    Rahul

    if I am doing something like this : for i in (execute immediate Lv_sql_query)
    I am getting an error which is :
    PLS-00103: Encountered the symbol "IMMEDIATE" when expecting one of the following:
    . ( ) , * @ % & | = - + < / > at in is mod remainder not
    range rem => .. <an exponent (**)> <> or != or ~= >=
    My code:
    create or replace procedure p_table_compare(fp_table_old in varchar2, fp_table_new in varchar2)
    as
    Lv_sql_query varchar2(2000);
    begin
         --dbms_output.put_line('Hello World');
         Lv_sql_query := 'select * from '||fp_table_old;
         for i in (execute immediate Lv_sql_query)
         loop
              dbms_output.put_line(i.employee_id);
         end loop;
    end;
    Please help.
    Regards
    Rahul

  • Pass table name to procedure

    hi
    Can any one plz suggest me , how to pass
    table name (that would be varchar) to a procedure,such that i
    should be able to do DML and DDL on the table refered !!

    EXECUTE IMMEDIATE executes the SQL statement held in a specified
    VARCHAR2. So, with a bit of string concatenation, you can make
    the statement dynamic, thus:
    EXECUTE IMMEDIATE 'DELETE * FROM emp' ;
    could become:
    EXECUTE IMMEDIATE 'DELETE * FROM '||p_table_name ;
    where p_table_name is a VARCHAR2 parameter passed into your
    procedure. Check out the PL/SQL User's Guide and Reference,
    chapter 10, for full details.

  • Invalid table name when pass in the table name as variable in dynamic sql

    Hi,
    I need to create a stored procedure which will return a list of data to my java application like the following.
    first, select the table name from the first table.
    For example : SELECT T_NAME FROM MDR_SMSTABLES
    second, select the data from the table which returned by first select statement
    For example : SELECT * FROM T_NAME.
    I use dynamic sql with cursor to select the data. But it returns "java.sql.SQLException: ORA-00903: invalid table name"
    I fetch the table name to varchar2. I think this might the cause it returns me the this error. But i don't know what type should i put for the table name other then varchar2.
    val2 VARCHAR2(200);
    OPEN cv FOR
    SELECT T_NAME FROM MDR_SMSTABLES WHERE T_DATE=d_dt_sent;
    FETCH cv INTO val2;
    WHILE cv%FOUND
    LOOP
    OPEN refcur FOR
    'SELECT * FROM :t WHERE MID = :m' USING val2, msg_id;
    EXIT WHEN refcur IS NOT NULL;
    FETCH cv INTO val2;
    END LOOP;
    As my stored procedure is quite long, so i just paste some of the code here. Hope the information is enough. Can anyone please help?
    Thanks

    DECLARE
    val2 VARCHAR2 (200);
    cv sys_refcursor;
    refcur sys_refcursor;
    BEGIN
    OPEN cv FOR
    SELECT table_name
    FROM user_tables
    WHERE table_name IN ('EMP', 'DEPT');
    FETCH cv INTO val2;
    WHILE cv%FOUND
    LOOP
    OPEN refcur FOR 'SELECT * FROM '||val2;
    EXIT WHEN refcur IS NOT NULL;
    FETCH cv INTO val2;
    END LOOP;
    END;

  • Passing table name to a report.

    I am designing an application that will draw data from any of a number of different tables (all with different data formats, but the same column names), and wish for this data to be displayed in a report. In the table that contains the selection criteria, I have included columns for schema name and table name. How can I pass these values into the report, and in turn, into a graph?
    I've tried this, but it doesn't work.
    SELECT data_column FROM
    :schema_column.:data_column;

    HI ,
    the table name can be easily passed on to the sql use lexicaly parameter as below
    SELECT data_column FROM
    &table_name where &where_clause
    once you write this query it will give you a message that a bind variable was created . Now you can assign value to this through parameter form or write a code in the after parameter form trigger and also generate the where clause if required .
    do you have same column name in different tables with different data types ?? if so then i really dont know how to solve this problem other wise it should not be a problem
    bye
    sudhir

  • Passing Table name as parameter to proc.

    Hi,
    I need to know how to pass a table name to a oracle procedure.
    In that procedure I will put that table name in a variable and then I will make operations on that table like DELETE, UPDATE and INSERT.
    Kinldy give me the solution for the above problem as soon as possible..
    Thanks & regards,
    Kiran

    You shouldn't do it, but if you do, you can use something like this:
    Anton
    create or replace type my_parm as object
      ( name varchar2(30)
      , val  anydata
    create or replace type my_parms as table of my_parm
    create table t1( c1 number, c2 varchar2(10), c3 date )
    create or replace procedure doital( p_action in varchar2, p_tab in varchar2, parms in my_parms )
    is
      p_stmt1 varchar2(32000);
      p_stmt2 varchar2(32000);
      ind pls_integer;
      curs integer;
      dummy integer;
      t_a anytype;
      t_v varchar2(32000);
      t_n number;
      t_d date;
    begin
      curs := dbms_sql.open_cursor;
      if upper( p_action ) = 'I'
      then
        ind := parms.first;
        loop
          exit when ind is null;
          p_stmt1 := p_stmt1 || ', ' || parms( ind ).name;
          p_stmt2 := p_stmt2 || ', :b' || to_char( ind );
          ind := parms.next( ind );
        end loop;
        p_stmt1 := 'insert into ' || p_tab || ' (' || substr( p_stmt1, 2 ) || ' ) values (' || substr( p_stmt2, 2 ) || ' )';
        dbms_sql.parse( curs, p_stmt1, dbms_sql.native );
        ind := parms.first;
        loop
          exit when ind is null;
          case parms( ind ).val.GetType( t_a )
            when dbms_types.typecode_varchar2
            then
              dummy := parms( ind ).val.GetVarchar2( t_v );
              dbms_sql.bind_variable( curs, ':b' || to_char( ind ), t_v );
            when dbms_types.typecode_number
            then
              dummy := parms( ind ).val.GetNumber( t_n );
              dbms_sql.bind_variable( curs, ':b' || to_char( ind ), t_n );
            when dbms_types.typecode_date
            then
              dummy := parms( ind ).val.GetDate( t_d );
              dbms_sql.bind_variable( curs, ':b' || to_char( ind ), t_d );
          end case;
          ind := parms.next( ind );
        end loop;
      end if;
      dummy := dbms_sql.execute( curs );
      dbms_sql.close_cursor( curs );
    end;
    begin
      doital( 'I', 't1', my_parms( my_parm( 'c2', anydata.ConvertVarchar2( 'testje' ) )
                                 , my_parm( 'c1', anydata.ConvertNumber( 3 ) )
                                 , my_parm( 'c3', anydata.ConvertDate( sysdate ) )
      doital( 'I', 't1', my_parms( my_parm( 'c1', anydata.ConvertNumber( 77 ) )
                                 , my_parm( 'c2', anydata.ConvertVarchar2( 'goedzo' ) )
                                 , my_parm( 'c3', anydata.ConvertDate( sysdate - 5 ) )
    end;
    /

  • Passing table names as parameters (aka Trouble building a dynamic SQL command)

    I am attempting to develop a template for publishing some data, and would like to pass standard table names as parameters to the various queries.  What I have created generates the following error:
    Msg 137, Level 16, State 1, Procedure spPublishTrans_FlashersCaution, Line 68
    Must declare the scalar variable "@tmpTable".
    I thought I was declaring it properly ?
    Thanks.
    DECLARE @FeatureClass as Nvarchar(MAX) = 'Trans_FlashersCaution'
    DECLARE @ED as Nvarchar(MAX) = 'edgis.dbo.' + @FeatureClass
    DECLARE @tmpTable TABLE
    [OBJECTID] [int] NOT NULL,
    [Id] [int] NULL,
    [Location] [nvarchar](60) NULL,
    [Zone] [nvarchar](5) NULL,
    [Shape] [geometry] NULL
    DECLARE @tmpTableParam AS NVARCHAR (MAX) = @tmpTable
    SELECT @tmpTableParam
    DECLARE @execquery AS NVARCHAR(MAX)
    SET @execquery = 'INSERT INTO' + @tmpTableParam +
    [OBJECTID]
    ,[Id]
    ,[Location]
    ,[Zone]
    ,[Shape]
    SELECT
    [OBJECTID]
    ,[Id]
    ,[Location]
    ,[Zone]
    ,[Shape]
    FROM' + @ED;
    EXECUTE sp_executesql @execquery

    Always PRINT the SQL string prior to execution when developing dynamic SQL script:
    PRINT @execquery
    --EXECUTE sp_executesql @execquery
    Second step, test the printed SQL script for validity.
    Dynamic SQL: http://www.sqlusa.com/bestpractices/dynamicsql/
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Database Design
    New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014

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

  • How to pass table name as argument to cursor

    please help me how to solve this.
    SQL> select c1 from test ;
    C1
    1
    7
    18
    4
    10
    28
    30
    I'm able to execute this.
    SQL> get b
    1 set serveroutput on size 2000
    2 declare
    3 cursor c1 is
    4 select c1 from test ;
    5 begin
    6 for rec in c1
    7 loop
    8 dbms_output.put_line(rec.c1);
    9 end loop;
    10* end;
    SQL> sta b
    1
    7
    18
    4
    10
    28
    30
    When I change the above cursor to accept the parameter it is not working.
    SQL> get c
    1 set serveroutput on size 2000
    2 declare
    3 cursor c1(p_table varchar2) is
    4 select c1 from p_table ;
    5 begin
    6 for rec in c1('test')
    7 loop
    8 dbms_output.put_line(rec.c1);
    9 end loop;
    10* end;
    ERROR at line 3:
    ORA-06550: line 3, column 18:
    PL/SQL: ORA-00942: table or view does not exist
    ORA-06550: line 3, column 3:
    PL/SQL: SQL Statement ignored
    ORA-06550: line 7, column 25:
    PLS-00364: loop index variable 'REC' use is invalid
    ORA-06550: line 7, column 4:
    PL/SQL: Statement ignored

    You cannot use a (bind) variable in SQL for an object name (i.e. a table name, column name, etc).
    Why?
    The SQL engine needs to parse the SQL. Part of the parse is to resolve the scope to determine what objects are being reference. It needs to check that the column names referred to is indeed in that object. Etc.
    Then these objects are used to determine the best execution path to run the SQL. What indexes do the objects have? Is the object a partitioned table and the partition criteria used in the predicate? Etc.
    How can the SQL engine perform any of these when you pass it a table name that is a parameter?
    The name of an object (such as the table being selected from) must be explicitly stated in a SQL statement. It cannot be variable.

Maybe you are looking for

  • When Logging in the user gets "The ID you entered was not found"

    I have UCCX v8.  All users can log in fine.  However, I have created a new user and they are getting "The ID you entered was not found". 1.  The user was created in CUCM, extension made available to UCCX, and device associated to RMuser account 2.  T

  • Put HTML reference on JSP

    Hi everybody, I'd like to have a web app based on jsp files which include different HTML files stored on Apache Web Server (on a different machine!!) Ex. Header.html, Menu.html and so on... I tried with Stuts tags but it seems not working with HTML f

  • Rogue reporting in WCS

    Can anybody tell me what the difference is between the following 2 default Security reports: Rogue APs Rouge APs Event WE run both of these nightly, but the Rogue APs Event report usually is about 20 pages or so, and the information there has way mor

  • Where's the opacity slider for brushes?

    I don't know why but I can't seem to find the opacity slider for my brush tool. I can see the general opacity of the layer, etc. but nothing specific to the brush. I've attached a screenshot that shows my working space. Thanks for any help. russ

  • Facebook notification

    I noticed saturday that I am no longer receiving facebook notifications, if I go to the app it will show that I have notifications, but its not alerting me.  I have deleted fb app & reloaded it, I reset my phone, & nothing is working.  Please help if