SQL: select into

Hello. In both sybase and sql server, you
can create on-the-fly tables in sql by
simply doing a
select column
into newtable
from oldtable
where blahblahblah
When I do the same in sql (not pl/sql)
I get the following error:
SQL> select empno
2 into myemp
3 from emp
4 where ename = 'SMITH';
into myemp
ERROR at line 2:
ORA-00905: missing keyword
Is it possible to do this kind of select into
in Oracle?
Thanks!

I believe the syntax you're looking for is:
create table <tablename>
as select *
from (<original statement>)
More examples are available in the Migration Workbench docs

Similar Messages

  • Pl/SQL Select Into

    Hello,
    is there a difference between the command 'select into' in Regions with 'pl/sql function returning Query' and 'Pl/sql amonymous block'.
    select MAX(maxgroups) into groupno from Table where trackid=:P_ITEM2 and col1=:P_ITEM2;
    This statement works only in the Region-'Pl/sql amonymous block.
    Can somebody help me please,
    I really can't find the reason!
    Moni

    Hi Marc,
    I' ve found out that the select statement works, the problem is that the items have no value.
    When I display the content of the item in the Region-Topic ‚Test – &P32_Item.’ it is displayed correctly.
    Maybe I’m calling the item in the pl/sql in a wrong way??
    lg
    Moni

  • SQL Select into Nested Table

    Hi,
    I would like to be able to store results of a query in the database. So far, I believe the best method is to store it as a nested table so that I may refer to it by criteria (e.g. date, name, etc.). I am somewhat new to Oracle and I'm not sure how to do this.
    The query will always return the same columns, so that should make it easier for me. Also, I need to be able to query the data that is stored into an APEX report region.
    Can someone tell me if this is the best method to do this? Also, is there a tutorial anywhere that explains how to do what I want?
    Thanks in advance,
    -David

    would like to be able to store results of a query in the database. So far,
    I believe the best method is to store it as a nested table so that I may refer
    to it by criteria (e.g. date, name, etc.). I am somewhat new to Oracle and
    I'm not sure how to do this.Given that you're new to Oracle how did you decide the best approach was a nested table? As most people who know anything at all about Oracle would take the opposite view (as Dan has done).
    Let's drill down into your requirements some more. How long do what to retain the results for? Do you want to retain the results of many queries? If so, will these queries be the same shape (same number and type of columns) or will they be different? Do you want one user to be able to see the results of another user's queries? Do you want to associate metadata with these result sets?
    In fact, why do you want to be able to store these result sets at all? Oracle is actually pretty good at caching data, especially in 11g. So you may be re-inventing a wheel and designing it wonky at that.
    Cheers, APC
    Blog : http://radiofreetooting.blogspot.com/

  • How to SELECT * into a SQL table incremntally by date?

    I have a SQL Server table called "tblProducts".
    Sometimes I backup this table by making a copy of it with this simple query:
    SELECT *
    INTO [test01].[dbo].[tblProducts_20141206]
    FROM [test01].[dbo].[tblProducts]
    Every time when making a backup, the date is included in the table name.
    I would like to create a SQL Job that runs this kind of query once every week.
    Is it possible to maybe in a stored procedure or declaring a variable to achieve this that allows the backed-up table name to be named like [tblProducts_todaysDate]?
    Thanks.

    hi ,dchencm
    i just want to point out the some bad effect of this pratice
    first point is
    when your db has be corrupt,your backup out of work
    i think you should backup your table to other db ensure that when your db has be corrupt you still have real backup
    just like
    SELECT *
    INTO [test01_backup].[dbo].[tblProducts_20141206]
    FROM [test01].[dbo].[tblProducts]
    another point is your pratice is total amount of backup not  incremental backup
    when your table  become bigger and bigger ,and then the number of record reach several million or several ten million or several hundred million, you must import all  data the table have
    so, this is not a good idea
    i just suggest  apply replication or logshipping etc to copy the diff data the table proceded is the better
     the steps of detail  as following
    step 1
    USE [test01]
    GO
    /****** 对象: StoredProcedure [dbo].[sp_ImportBackupData] 脚本日期: 12/25/2010 16:47:49 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE PROCEDURE [dbo].[sp_importbackupdata]
    AS
    BEGIN
    BEGIN
    DECLARE @date DATETIME ,
    @sql VARCHAR(1000)
    SET @date = GETDATE()
    SET @sql = 'SELECT * INTO [test01].[dbo].[tblProducts_'
    + CONVERT(VARCHAR(8), @date, 112)
    + '] FROM [test01].[dbo].[tblProducts]'
    EXEC (@Sql)
    END
    END
    step 2
    USE [msdb]
    GO
    /****** 对象: Job [import data] 脚本日期: 02/22/2011 09:22:44 ******/
    BEGIN TRANSACTION
    DECLARE @ReturnCode INT
    SELECT @ReturnCode = 0
    /****** 对象: JobCategory [Database Engine Tuning Advisor] 脚本日期: 02/22/2011 09:22:44 ******/
    IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'Database Engine Tuning Advisor' AND category_class=1)
    BEGIN
    EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'Database Engine Tuning Advisor'
    IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
    END
    DECLARE @jobId BINARY(16)
    EXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=N'sp_importbackupdata',
    @enabled=1,
    @notify_level_eventlog=0,
    @notify_level_email=0,
    @notify_level_netsend=0,
    @notify_level_page=0,
    @delete_level=0,
    @description=N'sp_importbackupdata',
    @category_name=N'Database Engine Tuning Advisor',
    @owner_login_name=N'sa', @job_id = @jobId OUTPUT
    IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
    /****** 对象: Step [import data] 脚本日期: 02/22/2011 09:22:44 ******/
    EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'import data',
    @step_id=1,
    @cmdexec_success_code=0,
    @on_success_action=1,
    @on_success_step_id=0,
    @on_fail_action=2,
    @on_fail_step_id=0,
    @retry_attempts=0,
    @retry_interval=0,
    @os_run_priority=0, @subsystem=N'TSQL',
    @command=N'exec sp_importbackupdata',
    @database_name=N'sss',
    @flags=0
    IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
    EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
    IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
    EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id=@jobId, @name=N'import frequency',
    @enabled=1,
    @freq_type=8,
    @freq_interval=2,
    @freq_subday_type=1,
    @freq_recurrence_factor=1,
    @active_start_time=20000
    IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
    EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
    IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
    COMMIT TRANSACTION
    GOTO EndSave
    QuitWithRollback:
    IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
    EndSave:
    the schedule time is 2 am  in the midnight  every monday 
    Certainly, you can edit it for yourself

  • MS-SQL - Oracle SELECT INTO conversion problem...

    Under MS-SQL (T-SQL) Select statement is defined as follows:
    SELECT select_list
    [INTO new_table_]
    ^^^^^^^^^^^^^^^^^^^^^
    FROM table_source
    [WHERE search_condition]
    [GROUP BY group_by_expression]
    [HAVING search_condition]
    [ORDER BY order_expression [ASC | DESC] ]
    Q:How under PL/SQL can one redirect sorted (ORDERed BY) results
    from SELECT query to another table.
    Slawek
    null

    I have asked the question because of the following reason:
    I have a large select query that returns rows from a table in
    different sort orders depending on user inputs, and I wonder if
    there is any way to return just the rows between two specified
    positions.
    I figured that I'm going to either create one temporary table
    with all the data (1000 records for example), sort the data in
    the prefered order and use the rownum method to obtain the row
    range (works fine under T-SQL). Other way is to try an inline
    view that return the rownumber. I can then restrict the numer of
    fields, e.g.
    select empid, rowNumber from emp,
    (select empid as id, rownum as rowNumber from emp) x
    where empid = id
    and rowNumber between 2 and 5
    The problem is that under Oracle the subquery is not allowed to
    have an ORDER BY clause (even if it had, rownum reflects row
    numbers before they were sorted) and there is no SELECT into
    TABLE_NAME.
    Michael Malicky (guest) wrote:
    : Slawek (guest) wrote:
    : : Under MS-SQL (T-SQL) Select statement is defined as follows:
    : : SELECT select_list
    : : [INTO new_table_]
    : : ^^^^^^^^^^^^^^^^^^^^^
    : : FROM table_source
    : : [WHERE search_condition]
    : : [GROUP BY group_by_expression]
    : : [HAVING search_condition]
    : : [ORDER BY order_expression [ASC | DESC] ]
    : : Q:How under PL/SQL can one redirect sorted (ORDERed BY)
    results
    : : from SELECT query to another table.
    : : Slawek
    : Order by is irrelevant when creating a new table out of a
    : query, as the rows are NOT stored in any order in a table.
    : The syntax for creating a new table out of an existing one
    : is:
    : CREATE TABLE new_table AS
    : SELECT select_list FROM old_table
    : WHERE ...
    : etc.
    : /mike
    null

  • "Select * into table internal_table from database_table" in native SQL

    Dear All,
    Is it possible to insert into internal table from database table in native sql instead of open sql? Regarding single values it's clear, just to use ":variable_name". But how to map internal table? RDBMS Oracle version > 9. If it's possible and you know how to do it, please, give some code example.
    Thank you,
    Pavel

    Hi ,
    Here is the code snippet for the native sql .
    select * from zwf_role into table i_wfroles." where role_id ='CAO'.
      loop at i_wfroles into wa_wfroles.
        EXEC sql.
          insert into   ROLES_MASTER_SAP
                 values (:wa_wfroles-ROLE_ID,:wa_wfroles-ROLE_NM,
                        :wa_wfroles-ROLE_DESC,:wa_wfroles-PAR_ROLE_ID,
                        :wa_wfroles-WF_ROLE_ORDER,:wa_wfroles-ROLE_TYPE )
        ENDEXEC.
        if sy-subrc = 0 .
          suc_rec_cnt = suc_rec_cnt + 1.
        else.
          fail_rec_cnt = fail_rec_cnt + 1.
        endif.
    *              ( ROLE_ID,ROLE_NAME, ROLE_DESC,PARENT_ROLE_ID,ROLE_ORDER,
    *                  ROLE_TYPE )
      endloop.
    zwf_role database table has the same files
    Regards
    Girish

  • Can I put a SQL query into a bind variable and then use it to output report

    Hi,
    Can I put a SQL query into a bind variable and then use it to output report?
    I want to create a report and an item "text area" (say P1_TEXT) which can let user to input a SQL query(they are all technical users and knows SQL very well). Then, I use a bind variable (that text area) to store the SQL statement. Then, I add a submit button and I want to use the following to output the report:
    select * from (:P1_TEXT);
    Do you think it is possible to do that? Any known limitations for APEX in this area?
    Thanks a lot,
    Angela

    You can, but make sure it's what you really want to do. Make sure you are VERY familiar with SQL Injection. Most people who know what it is, go out of their way to prevent SQL Injection. You're going out of your way to allow it.
    You can try using &P1_TEXT. instead of bind variable syntax. Bind variables are one of the best ways to prevent SQL Injection, which is why it's not working for you.
    Once again, I strongly urge you to consider the implications of your app, but this suggestion should get it working.
    Tyler

  • Sql select query problem

    hi friends,
    i've a view called "risk_efforts" with fields user_id,user_name,wknd_dt,week_day,prod_efforts,unprod_efforts.
    Name Type
    ROW_ID NUMBER
    USER_ID VARCHAR2(14)
    USER_NAME VARCHAR2(50)
    WKND_DT VARCHAR2(8)
    WEEK_DAY VARCHAR2(250)
    PROD_EFFORTS NUMBER
    UNPROD_EFFORTS NUMBER
    data is like this:
    when there is some data in prod_efforts, unprod_efforts will be null
    when there is some data in unprod_efforts, prod_efforts will be null
    for example:
    USER_ID     USER_NAME     WKND_DT     WEEK_DAY     PROD_EFFORTS     UNPROD_EFFORTS
    G666999     GTest     20100403     TUE     null 3
    G666999     GTest     20100403     TUE     14     null
    now i want to combine these 2 rows into 1 row i.e o/p should be like this
    USER_ID     USER_NAME     WKND_DT     WEEK_DAY     PROD_EFFORTS     UNPROD_EFFORTS
    G666999     GTest     20100403     TUE     14 3
    i've tried all combinations but couldn't get the query. Please help me with the exact SQL select query.
    thanks,
    Girish

    Welcome to the forum.
    First read this:
    Urgency in online postings
    Secondly, it's always helpful to provide the following:
    1. Oracle version (SELECT * FROM V$VERSION)
    2. Sample data in the form of CREATE / INSERT statements.
    3. Expected output
    4. Explanation of expected output (A.K.A. "business logic")
    5. Use \ tags for #2 and #3. See FAQ (Link on top right side) for details.
    You have provided #3 and #4. However with no usable form of sample data forum members will often not respond as quickly as they could if you provided #2.
    I'm just wagering a guess here but what about this:SELECT ROW_ID
    , USER_ID
    , WKND_DT
    , WEEK_DAY
    , MAX(PROD_EFFORTS) AS PROD_EFFORTS
    , MAX(UNPROD_EFFORTS) AS UNPROD_EFFORTS
    FROM RISK_EFFORTS
    GROUP BY ROW_ID
    , USER_ID
    , WKND_DT
    , WEEK_DAY                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Select Into statement in db function - query from granted schema table

    problem with "select into" in db function in 10.2
    There are two schemas. 'mdbdev' is the master database and 'devusr' is granted SELECT table access to execute queries in mdbdev schema.
    with devusr, in SQL, I'm able to execute the following query
    select wm_concat(strConcatedCountryList)
    from (select country_name as strConcatedCountryList from mdbdev.country_master mdbcm
    where mdbcm.country_ship_status = <param?>
    order by country_name)
    but when I use the same query in function/procedure with "select into", the compilation failed with error *"table or view does not exist"*
    FUNCTION GETCOUNTRYLISTTOSHIP (SHIP_STATUS IN NUMBER)
    RETURN VARCHAR2
    IS
    var2CountryList VARCHAR2(1000);
    BEGIN
    select wm_concat(strConcatedCountryList) INTO var2CountryList
    from (select country_name as strConcatedCountryList from mdbdev.country_master mdbcm
    where mdbcm.country_ship_status = <value of SHIP_STATUS>
    order by country_name);
    return var2CountryList;
    END;
    Please advise/help/hint :)

    David, Justine, Thank you. The facts from this forum post helped a lot to get the solution.
    The query helped a lot (select * from all_tab_privs_recd where owner = 'MDBDEV' and table_name = 'COUNTRY_MASTER").
    there was a grant using ???(donno wht DBA said) and no direct SELECT grant on that country_master to "devusr". grant command executed. Now, it works :)

  • Dynamic PL/SQL block vs dynamic SQL SELECT

    Hi there,
    I have a question regarding the optimal way to code a dynamic SELECT INTO statement. Below are the 2 posiibilities I know of:
    _1. Dynamically executing the SELECT statement and making use of the INTO clause of the EXECUTE IMMEDIATE statement_
    CREATE OR REPLACE FUNCTION get_num_of_employees (p_loc VARCHAR2, p_job VARCHAR2)
    RETURN NUMBER
    IS
    v_query_str VARCHAR2(1000);
    v_num_of_employees NUMBER;
    BEGIN
    v_query_str := 'SELECT COUNT(*) FROM emp_'
    || p_loc
    || ' WHERE job = :bind_job';
    EXECUTE IMMEDIATE v_query_str
    INTO v_num_of_employees
    USING p_job;
    RETURN v_num_of_employees;
    END;
    _2. Encapsulating the SELECT INTO statement in a block and dynamically exectuting the block_
    CREATE OR REPLACE FUNCTION get_num_of_employees (p_loc VARCHAR2, p_job VARCHAR2)
    RETURN NUMBER
    IS
    v_query_str VARCHAR2(1000);
    v_num_of_employees NUMBER;
    BEGIN
    v_query_str := 'begin
    SELECT COUNT(*) INTO :into_bind FROM emp_'
    || p_loc
    || ' WHERE job = :bind_job;
    end;';
    EXECUTE IMMEDIATE v_query_str
    USING out v_num_of_employees, p_job;
    RETURN v_num_of_employees;
    END;
    I was just wondering which way would be preferred? I know the second method uses a bind variable for the INTO clause, but does the first one also use bind varialbes (no semi-colon)? Any differences in terms of efficiency or speed?
    Thanks alot
    Edited by: BYS2 on Oct 19, 2011 1:23 AM

    sybrand_b wrote:
    No difference in terms of performance or speed
    Both variants will wreck the primary purpose of PL/SQL: to avoid parsing.
    When I would see a 'developer' do this, I would fire him on the spot.
    Why abuse PL/SQL in such a fashion? Both statements don't require parsing, as there is nothing dynamic in them and indicate a complete lack of understanding of Oracle, or a desire to deliver completely unscalable applications, resulting in end-users desiring to lynch you, and rightly so.
    Remove the dynamic SQL or find another job.
    Sybrand Bakker
    Senior Oracle DBANot dynamic? What if p_loc and p_job were generated dynamically based on user-input? or what if there were potentially thousands of tables that p_loc could refer to? Should I make a CASE statement with a thousand cases?
    In addition, the first example was actually taken directly from the official Oracle Database Application Developer's Guide (version 10.2). http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14251/adfns_dynamic_sql.htm#i1006429 - look under 'Sample Single-Row Query Using Native Dynamic SQL' heading. Therefore, if you have any issues with this alleged 'improper' usage of dynamic SQL, perhaps you should go talk to Oracle directly.
    While I appreciate your response, I don't think it has occurred that you that not everyone is a 'developer'. In fact, I have only very recently (several days ago) taught myself how to use Oracle SQL, PL/SQL and XMLDB by reading several of the official Oracle language and developer's guides. It is more a passing interest to me as I am working on some medical research which may require the use of a database. I am actually in medical school at the moment but have an undergraduate degree in Electrical and Computer engineering so I am generally well-versed in programming.
    Perhaps the next time, you post your rubbish, rude and unhelpful comments, you should stop and think that people come to this forum because they need help and not because they want to be told to 'find another job'. In fact, I am quite certain that I could make you look absolutely stupid in any topic of electrical engineering or medicine.
    Please do us all a favour and stop polluting this forum with your vapid posts. While I understand that your behavior is likely a compensatory mechanism to cope with your inferiority complex, know that help IS available if you need it.
    Edited by: BYS2 on Oct 19, 2011 2:13 AM

  • How to exit from SQL*Plus based on the return value of a SQL select stment?

    Hi
    I have a SQL script executed from SQL*Plus. I would like to know if SQL*Plus
    supports any kind of branching or exiting from script execution based on a
    returned value of a SQL select statement. I am on 9i.
    Regards,
    Tamas Szecsy

    in sqlplus, you have whenever
    ex:
    whenever sqlerror exit failure
    insert into ...
    -- if this fails, then you will be out
    insert into ...
    -- if this fails, then you will be out
    whenever sqlerror continue
    insert into ...
    -- if this fails, this continues
    insert into ...and you have PL/SQL
    declare x number;
    begin
    select count(*) into x from emp;
    if (x=14) then null; end if;
    end;
    /note that you can mix those in some case
    -- exit if there is no row in emp
    whenever sqlerror exit 1
    var dummy number
    exec select count(*) into :dummy from emp having count(*)!=0

  • Lookup by SQL select in ODS tables and source package

    Hi all
    I load FI data in ODS and need some extra info from older ODS records.
    In my Update rule for target InfoObject I created 2 SQL selects on Active Data and New data tables of ODS. Selects worked fine while testing them as separate program, but I got no data while data load.
    I guess, the data I need was in the same data package during data load. So I assume, besides Active/New data selects, I need to check data on SOURCE_PACKAGE. Is it possible on update rule level of InfoObject? Could you please, provide me some ABAP example?
    thanx in advance, points will be awarded.

    SELECT in field routine:
    ==========================================================
          DATA src_doc_no(10) TYPE c.
          DATA src_item_num(3) TYPE c.
          DATA src_year(5) TYPE c.
          DATA src_doc_typ(2) TYPE c.
      if ( COMM_STRUCTURE-AC_DOC_TYP = 'DD' or COMM_STRUCTURE-AC_DOC_TYP =
      'LD' ) and STRLEN( COMM_STRUCTURE-REF_KEY3 ) = 17.
         CONCATENATE COMM_STRUCTURE-REF_KEY3+0(4) '%' INTO src_year.
         src_item_num = COMM_STRUCTURE-REF_KEY3+15(3).
         src_doc_no = COMM_STRUCTURE-REF_KEY3+4(10).
    select from NEW data of ODS:
         SELECT AC_DOC_TYP into src_doc_typ
         FROM /BI0/AFIAR_O0340
         WHERE COMP_CODE = COMM_STRUCTURE-COMP_CODE
           AND DEBITOR = COMM_STRUCTURE-DEBITOR
           AND FISCVARNT = COMM_STRUCTURE-FISCVARNT
           AND AC_DOC_NO = src_doc_no
           AND ITEM_NUM = src_item_num
           AND FISCPER like src_year.
         endselect.
         if src_doc_typ = ''.
    select from ACTIVE data of ODS:
           SELECT AC_DOC_TYP into src_doc_typ
           FROM /BI0/AFIAR_O0300
           WHERE COMP_CODE = COMM_STRUCTURE-COMP_CODE
             AND DEBITOR = COMM_STRUCTURE-DEBITOR
             AND FISCVARNT = COMM_STRUCTURE-FISCVARNT
             AND AC_DOC_NO = src_doc_no
             AND ITEM_NUM = src_item_num
             AND FISCPER like src_year.
           endselect.
         endif.
         RESULT = src_doc_typ.
      endif.
    ============================================

  • Using column number inplace of column name in SQL Select statement

    Is there a way to run sql select statements with column numbers in
    place of column names?
    Current SQL
    select AddressId,Name,City from AddressIs this possible
    select 1,2,5 from AddressThanks in Advance

    user10962462 wrote:
    well, ok, it's not possible with SQL, but how about PL/SQL?As mentioned, using DBMS_SQL you can only really use positional notation... and you can also use those positions to get the other information such as what the column is called, what it's datatype is etc.
    CREATE OR REPLACE PROCEDURE run_query(p_sql IN VARCHAR2) IS
      v_v_val     VARCHAR2(4000);
      v_n_val     NUMBER;
      v_d_val     DATE;
      v_ret       NUMBER;
      c           NUMBER;
      d           NUMBER;
      col_cnt     INTEGER;
      f           BOOLEAN;
      rec_tab     DBMS_SQL.DESC_TAB;
      col_num     NUMBER;
      v_rowcount  NUMBER := 0;
    BEGIN
      -- create a cursor
      c := DBMS_SQL.OPEN_CURSOR;
      -- parse the SQL statement into the cursor
      DBMS_SQL.PARSE(c, p_sql, DBMS_SQL.NATIVE);
      -- execute the cursor
      d := DBMS_SQL.EXECUTE(c);
      -- Describe the columns returned by the SQL statement
      DBMS_SQL.DESCRIBE_COLUMNS(c, col_cnt, rec_tab);
      -- Bind local return variables to the various columns based on their types
      FOR j in 1..col_cnt
      LOOP
        CASE rec_tab(j).col_type
          WHEN 1 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000); -- Varchar2
          WHEN 2 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_n_val);      -- Number
          WHEN 12 THEN DBMS_SQL.DEFINE_COLUMN(c,j,v_d_val);     -- Date
        ELSE
          DBMS_SQL.DEFINE_COLUMN(c,j,v_v_val,2000);  -- Any other type return as varchar2
        END CASE;
      END LOOP;
      -- Display what columns are being returned...
      DBMS_OUTPUT.PUT_LINE('-- Columns --');
      FOR j in 1..col_cnt
      LOOP
        DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' - '||case rec_tab(j).col_type when 1 then 'VARCHAR2'
                                                                                  when 2 then 'NUMBER'
                                                                                  when 12 then 'DATE'
                                                         else 'Other' end);
      END LOOP;
      DBMS_OUTPUT.PUT_LINE('-------------');
      -- This part outputs the DATA
      LOOP
        -- Fetch a row of data through the cursor
        v_ret := DBMS_SQL.FETCH_ROWS(c);
        -- Exit when no more rows
        EXIT WHEN v_ret = 0;
        v_rowcount := v_rowcount + 1;
        DBMS_OUTPUT.PUT_LINE('Row: '||v_rowcount);
        DBMS_OUTPUT.PUT_LINE('--------------');
        -- Fetch the value of each column from the row
        FOR j in 1..col_cnt
        LOOP
          -- Fetch each column into the correct data type based on the description of the column
          CASE rec_tab(j).col_type
            WHEN 1  THEN DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
                         DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' : '||v_v_val);
            WHEN 2  THEN DBMS_SQL.COLUMN_VALUE(c,j,v_n_val);
                         DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' : '||v_n_val);
            WHEN 12 THEN DBMS_SQL.COLUMN_VALUE(c,j,v_d_val);
                         DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' : '||to_char(v_d_val,'DD/MM/YYYY HH24:MI:SS'));
          ELSE
            DBMS_SQL.COLUMN_VALUE(c,j,v_v_val);
            DBMS_OUTPUT.PUT_LINE(rec_tab(j).col_name||' : '||v_v_val);
          END CASE;
        END LOOP;
        DBMS_OUTPUT.PUT_LINE('--------------');
      END LOOP;
      -- Close the cursor now we have finished with it
      DBMS_SQL.CLOSE_CURSOR(c);
    END;
    SQL> exec run_query('select empno, ename, deptno, sal from emp where deptno = 10');
    -- Columns --
    EMPNO - NUMBER
    ENAME - VARCHAR2
    DEPTNO - NUMBER
    SAL - NUMBER
    Row: 1
    EMPNO : 7782
    ENAME : CLARK
    DEPTNO : 10
    SAL : 2450
    Row: 2
    EMPNO : 7839
    ENAME : KING
    DEPTNO : 10
    SAL : 5000
    Row: 3
    EMPNO : 7934
    ENAME : MILLER
    DEPTNO : 10
    SAL : 1300
    PL/SQL procedure successfully completed.
    SQL> exec run_query('select * from emp where deptno = 10');
    -- Columns --
    EMPNO - NUMBER
    ENAME - VARCHAR2
    JOB - VARCHAR2
    MGR - NUMBER
    HIREDATE - DATE
    SAL - NUMBER
    COMM - NUMBER
    DEPTNO - NUMBER
    Row: 1
    EMPNO : 7782
    ENAME : CLARK
    JOB : MANAGER
    MGR : 7839
    HIREDATE : 09/06/1981 00:00:00
    SAL : 2450
    COMM :
    DEPTNO : 10
    Row: 2
    EMPNO : 7839
    ENAME : KING
    JOB : PRESIDENT
    MGR :
    HIREDATE : 17/11/1981 00:00:00
    SAL : 5000
    COMM :
    DEPTNO : 10
    Row: 3
    EMPNO : 7934
    ENAME : MILLER
    JOB : CLERK
    MGR : 7782
    HIREDATE : 23/01/1982 00:00:00
    SAL : 1300
    COMM :
    DEPTNO : 10
    PL/SQL procedure successfully completed.
    SQL> exec run_query('select * from dept where deptno = 10');
    -- Columns --
    DEPTNO - NUMBER
    DNAME - VARCHAR2
    LOC - VARCHAR2
    Row: 1
    DEPTNO : 10
    DNAME : ACCOUNTING
    LOC : NEW YORK
    PL/SQL procedure successfully completed.
    SQL>

  • Dynamic column name with SELECT INTO

    I am trying to build a function that derives a pay amount from a set of business rules. There are about 40 columns that hold various pay amounts and their column names are variations of 4 indicators (day shift, vs night shift, etc.) that I have to dynamically look up, ie here is the ID number and a timecard, now figure out which of the 40 fields to look up to get the pay amount.
    I can determine from the timecard and employee ID which field to look at, but I'm getting hung up with the syntax needed to construct and execute the statement inside the PL/SQL block. I need to RETURN the pay I extract using the function, and I can create the correct SQL statement, but the EXECUTE IMMEDIATE won't accept the SELECT INTO syntax.
    Can someone please suggest a solution? Here is the function:
    create or replace FUNCTION FN_GET_PAYRATE(tc in NUMBER, e in NUMBER, pc in VARCHAR2)
    RETURN NUMBER
    IS
    e_id NUMBER;
    tc_id NUMBER;
    pl_cd VARCHAR2(7);
    shft VARCHAR2(2);
    lvl VARCHAR2(2);
    typ VARCHAR2(2);
    e_typ VARCHAR2(4);
    proj NUMBER;
    hrly VARCHAR2(4);
    payrt NUMBER;
    var_col VARCHAR2(10);
    sql_select VARCHAR2(200);
    sql_from VARCHAR2(200);
    sql_where VARCHAR2(200);
    sql_and1 VARCHAR2(200);
    sql_and2 VARCHAR2(200);
    sql_and3 VARCHAR2(200);
    sql_orderby VARCHAR2(200);
    var_sql VARCHAR2(2000);
    BEGIN
    e_id := e;
    tc_id := tc;
    pl_cd := pc;
    SELECT NVL(SHIFT,'D') INTO shft
    FROM TS_TIMECARD_MAIN
    WHERE TIMECARD_ID = tc_id;
    --DBMS_OUTPUT.PUT_LINE('SHIFT= ' || shft);
    SELECT NVL(PAY_LVL, 1), NVL(PAY_TYPE, 'B'), NVL(RTRIM(EMP_TYPE), 'LHD'), NVL(PROJECT, 001)
    INTO lvl, typ, e_typ, proj
    FROM TS_EMPLOYEES
    WHERE EMP_ID = e_id;
    --DBMS_OUTPUT.PUT_LINE('Level= ' || lvl);
    --DBMS_OUTPUT.PUT_LINE('PAY_TYPE= ' || typ);
    --DBMS_OUTPUT.PUT_LINE('EMP_TYPE= ' || e_typ);
    --DBMS_OUTPUT.PUT_LINE('PROJECT= ' || proj);
    IF e_typ <> 'LHD' THEN
    hrly := 'H';
    ELSE
    hrly := '';
    END IF;
    IF proj <> 001 THEN
    var_col := shft || lvl || typ || hrly;
    --DBMS_OUTPUT.PUT_LINE('RATE COLUMN= ' || var_col);
    sql_select := 'SELECT NVL(' || var_col || ', .01) INTO payrt';
    sql_from := ' FROM TS_PAYRATES';
    sql_where := ' WHERE PROJECT_ID = ' || proj;
    sql_and1 := ' AND ACTIVE = 1';
    sql_and2 := ' AND JOB_TYPE = ' || CHR(39) || e_typ || CHR(39);
    sql_and3 := ' AND PILE_ID = ' || CHR(39) || pl_cd || CHR(39);
    var_sql := sql_select || sql_from || sql_where || sql_and1 || sql_and2 || sql_and3 || sql_orderby;
    DBMS_OUTPUT.PUT_LINE('SQL: ' || var_sql);
    EXECUTE IMMEDIATE var_sql;
    DBMS_OUTPUT.PUT_LINE('RATE= ' || payrt);
    RETURN payrt;
    ELSE
    DBMS_OUTPUT.PUT_LINE('ERROR');
    RETURN 1;
    END IF;
    END;
    I have alternately tried this:
    SELECT NVL(var_col,.01) into payrt
    FROM TS_PAYRATES
    WHERE PROJECT_ID = proj AND ACTIVE = 1
    AND JOB_TYPE = CHR(39) || e_typ || CHR(39)
    AND PILE_ID = CHR(39) || pl_cd || CHR(39);
    as a substitute for the EXECUTE IMMEDIATE block, but I can't seem to use a dynamic substitution for the column name.
    Any help would be greatly appreciated.

    That's the most difficult part - the error messages seem to indicate a problem with the SQL statement in its execution context, because I can take the SQL string by itself and it executes perfectly.
    Here are three variations:
    SELECT INTO
    select fn_get_payrate(21555, 30162, 15) from dual
    ERROR at line 1:
    ORA-00905: missing keyword
    ORA-06512: at "PEOPLENETIF.FN_GET_PAYRATE", line 60
    SQL: SELECT NVL(N4P , .01) INTO payrt FROM TS_PAYRATES WHERE PROJECT_ID = 701 AND ACTIVE = 1 AND JOB_TYPE = 'LHD' AND PILE_ID = '15'
    Without SELECT INTO  (returns NULL)
    SQL> select fn_get_payrate(21555, 30162, 15) from dual;
    FN_GET_PAYRATE(21555,30162,15)
    SQL: SELECT NVL(N4P , .01) FROM TS_PAYRATES WHERE PROJECT_ID = 701 AND ACTIVE = 1 AND JOB_TYPE = 'LHD' AND PILE_ID = '15'
    RATE=
    EXECUTE IMMEDIATE USING
    SQL> select fn_get_payrate(21555, 30162, 15) from dual;
    select fn_get_payrate(21555, 30162, 15) from dual
    ERROR at line 1:
    ORA-01006: bind variable does not exist
    ORA-06512: at "PEOPLENETIF.FN_GET_PAYRATE", line 61
    SQL: SELECT NVL(N4P , .01) FROM TS_PAYRATES WHERE PROJECT_ID = 701 AND ACTIVE = 1 AND JOB_TYPE = 'LHD' AND PILE_ID = '15'

  • SELECT INTO doing case insensitive query?

    Hi all,
    I'm having a problem with a query acting as if it is case-insensitive when I do a "SELECT table.x INTO variable ...". If I do the same query, without the "INTO variable", I get one result, as expected.
    The query is similar to the following:
    SELECT table_id INTO variable FROM table WHERE table.varchar2column = 'name' AND table.integercolumn = int_variable;
    There is a unique constraint forcing the varchar2column / integercolumn values to be unique.
    If the varchar2column has two entries that differ only in case, a regular select statement returns one result. However, in the stored procedure using the INTO, I get the following error message:
    ORA-01422: exact fetch returns more than requested number of rows
    It does not get that if I remove the entry that differs only in letter-case. This is Oracle 10.2.0.1.0, if that matters.
    I need this query to be case sensitive. I'm not a DB expert, I'm just a developer trying to fix a problem. I attempted to run "ALTER session SET nls_sort = binary" in the stored procedure, but I guess I can't do that...
    Any suggestions would be appreciated.

    791307 wrote:
    SELECT table_id INTO variable FROM table WHERE table.varchar2column = 'name' AND table.integercolumn = int_variable;
    ...When you say, "...AND table.integercolumn = int_variable;" What is the name of int_variable? Does that name match some column name? Could you post the table creats and a complete sample PL/SQL block with your issue?
    One of the things that gets me every once in awhile is having a variable name that matches a column name. In that case the column name is used inside the select statement, not the variable. To avoid that issue, I use v_ for all my variables. (Others have different standard prefixes.)
    I only point this out, because it might be given results that look case insensitive on the varchar2 column, but is really an issue with the integer column matching to a variable:
    SQL> drop table T;
    Table dropped.
    SQL> create table T (id number constraint T_PK primary key
      2      , Varchar2Data varchar2(20)
      3      , NumberData number(38)
      4      , constraint T_UK1 unique (Varchar2Data, NumberData)
      5  );
    Table created.
    SQL> insert into T values (1, 'STRING', 100);
    1 row created.
    SQL> insert into T values (2, 'string', 200);
    1 row created.
    SQL> insert into T values (3, 'STRING', 300);
    1 row created.
    SQL> select * from T where Varchar2Data = 'STRING' and NumberData = 100;
            ID VARCHAR2DATA         NUMBERDATA
             1 STRING                      100
    SQL> declare
      2      NumberData number(38);
      3      Id Number;
      4  begin
      5      NumberData := 100;
      6      select Id into Id
      7      from T
      8      where T.Varchar2Data = 'STRING'
      9      and T.NumberData = NumberData;
    10      DBMS_OUTPUT.PUT_LINE(Id);
    11  end;
    12  /
    declare
    ERROR at line 1:
    ORA-01422: exact fetch returns more than requested number of rows
    ORA-06512: at line 6
    SQL> declare
      2      v_NumberData number(38);
      3      v_Id Number;
      4  begin
      5      v_NumberData := 100;
      6      select Id into v_Id
      7      from T
      8      where T.Varchar2Data = 'STRING'
      9      and T.NumberData = v_NumberData;
    10      DBMS_OUTPUT.PUT_LINE(v_Id);
    11  end;
    12  /
    1
    PL/SQL procedure successfully completed.
    SQL>

Maybe you are looking for

  • I am going to buy a new external hard drive and have some questions first

    Although I asked this question several years ago, I would like to ask it again, just if in case technology in general or external hard drives in particular have changed in any significant ways. I need to replace a 1 terabyte LaCie external hard drive

  • M : M mapping EJBs

    Hi, I have managed to set up a many to many relationship in my ejb-xml.jar and orion-ejb-jar.xml and this works just fine for this scenario... many TASKINGs have many PERSONs so the TASKING.ID and PERSON.ID are created in a new link table. I can upda

  • My photos downloaded as negatives

    New ipad I downloaded my phots from the PC but they appear as negatives on the ipad. ???

  • Ideas for carrying earphones

    Does anyone have any ideas for the storage of earphones? I just bought a Sena case for my IPT, but am not sure how to store my earphones in my purse so that they won't get tangled, and so they are easily accessible.

  • How to run Adobe Acrobat Action as a service

    we are using Acrobat XI and I have a custom action that is run manually.  What I am interested in is seeing if there is a way to invoke this action automatically once a file gets added to the folder. Thanks, JARED