PL/SQL cursor help

Dear Experts,

I need help, writing / editing PL/SQL procedure below. My task is to rebuild indexes on tables that were not rebuilt during the last 24 hours. The "select" statement of down gives me the list of all the names of tables whose indexes are not rebuilt in last 24 hours (maint.index_rebuild is a custom table, we built to capture the rebuild index timings).

maint.online_reorg procedure done index rebuild. I need this procedure to run on all tables (returned by the select statement). How can I get the modified procedure to get what I'm looking for below. Enjoy your entries.

declare cursor c1 is
select distinct table_name from maint.index_rebuild where start_time <= SYSDATE-1;
begin
for i in c1 loop
maint.online_reorg('OWNER','table name from cursor result set');
end loop;
end;
/
declare
  cursor c1 is
    select distinct table_name from maint.index_rebuild where start_time <= SYSDATE-1;
begin
  for i in c1 loop
    maint.online_reorg('OWNER',i.table_name);
  end loop;
end;

will do what you ask. As others have pointed out, however, what you're trying to do is strongly discouraged. Reconstruction of each index everyday is going to generate a huge amount of load on your database for no benefit and creates a number of opportunities to introduce errors.

Justin

Tags: Database

Similar Questions

  • PL/SQL: cursor already open

    Hi all

    You people could help to resolve the error
    "PL/SQL: cursor already open '."

    Thanks in advance
     CREATE OR REPLACE FUNCTION get_row_lane_counts_text
     RETURN VARCHAR2
     IS
        my_row_counts_text      VARCHAR2(10000);
        my_row_counts_entry      VARCHAR2(10000);
        my_row_counts_pct_entry      VARCHAR2(10000);      
        my_row_count_total_text  VARCHAR2(10000);
        my_total            NUMBER(12);
        my_count_result     VARCHAR2(20);
     
        CURSOR row_counts_text IS
            SELECT 'edr_rpt_lane_by_class_package.gen_total_lane_count('
                            ||'lane_id, '
                            ||'direction_id, '
                            ||'interval_start_date_time, '
                            ||'interval_end_date_time, '
                            ||'range_low, '
                            ||'range_high, '
                            || site_lane_id || ', '                                        
                            || site_lane_id || ') "#'|| site_lane_id || '"'
              FROM edr_rpt_tmp_report_lanes     
          ORDER BY site_lane_id;
          
           CURSOR row_counts_pct_text IS
            SELECT 'edr_rpt_lane_by_class_package.gen_total_lane_count_pct('
                            ||'lane_id, '
                            ||'direction_id, '
                            ||'interval_start_date_time, '
                            ||'interval_end_date_time, '
                            ||'range_low, '
                            ||'range_high, '
                            || site_lane_id || ', '                                        
                            || site_lane_id || ') "#'|| site_lane_id || '%"'
              FROM edr_rpt_tmp_report_lanes     
          ORDER BY site_lane_id;
          
          
     
     BEGIN
     
       my_row_counts_text      := ''; 
       my_row_counts_entry     := '';
       my_row_counts_pct_entry := ''; 
      
       -- generate the speed ranges function calls
       OPEN row_counts_text;
       LOOP
     
         FETCH row_counts_text INTO my_row_counts_entry;
     
         EXIT WHEN row_counts_text%NOTFOUND;
         
              OPEN row_counts_pct_text;
            LOOP
     
                  FETCH row_counts_pct_text INTO my_row_counts_pct_entry;
     
                  EXIT WHEN row_counts_pct_text%NOTFOUND;
         
                 my_row_counts_text := my_row_counts_entry || ', ' || my_row_counts_pct_entry;
             
             END LOOP; 
             
            
        
       END LOOP;
       
         CLOSE row_counts_pct_text;
       
       CLOSE row_counts_text;
       
       
     
       RETURN my_row_counts_text;
       
     
     END;
     /

    Works fine for me...

    SQL > create table t1 (number, number of b).

    Table created.

    SQL > insert into t1 values (1,1);

    1 line of creation.

    SQL > commit;

    Validation complete.

    SQL > CREATE or REPLACE FUNCTION get_row_lane_counts_text
    2 RETURN VARCHAR2
    3 EAST
    4 my_row_counts_text VARCHAR2 (10000);
    5 my_row_counts_entry VARCHAR2 (10000);
    6 my_row_counts_pct_entry VARCHAR2 (10000);
    7 my_row_count_total_text VARCHAR2 (10000);
    8 my_total NUMBER (12);
    9 my_count_result VARCHAR2 (20);
    10
    11 row_counts_text of CURSOR IS
    12. SELECT one
    13 FROM t1;
    14
    15
    16
    17 row_counts_pct_text of CURSOR IS
    18 SELECT b
    19 FROM t1;
    20
    21
    22
    23
    24
    BEGIN 25
    26
    27
    28 my_row_counts_text: = ";
    29 my_row_counts_entry: = ";
    30 my_row_counts_pct_entry: = ";
    31
    32
    33 generates speed ranges function calls
    34 row_counts_text OPEN;
    LOOP 35
    36
    37
    38 FETCH row_counts_text INTO my_row_counts_entry;
    39
    40
    EXIT 41 WHEN row_counts_text % NOTFOUND;
    42
    43
    44 row_counts_pct_text OPEN;
    45 LOOP
    46
    47
    48 FETCH row_counts_pct_text INTO my_row_counts_pct_entry;
    49
    50
    EXIT 51 WHEN row_counts_pct_text % NOTFOUND;
    52
    53
    54 my_row_counts_text: = my_row_counts_entry | ', ' || my_row_counts_pct_entry;
    55
    56
    57 END LOOP;
    58
    59
    60 row_counts_pct_text CLOSE;
    61
    LOOP END 62;
    63
    64
    65
    66
    67
    68 row_counts_text CLOSE;
    69
    70
    71
    72
    73 my_row_counts_text RETURN;
    74
    75
    76
    END 77;
    78
    79.

    The function is created.

    SQL >

    SQL > select get_row_lane_counts_text() from double;

    GET_ROW_LANE_COUNTS_TEXT()
    --------------------------------------------------------------------------------
    1, 1

  • Same mistake again - ORA-06511: PL/SQL: cursor already opened

    Hello

    Even if I close the cursor, I get the following error "ORA-06511-6511: PL/SQL: cursor already opened. Please can you give your suggestion.

    CUR CURSOR IS
    JULIE name FROM test;

    BEGIN

    IF heart % ISOPEN THEN
    CLOSE cur
    END IF;

    Heart OPEN;

    FOR my heart IN cuv
    LOOP
    -sql statements
    END LOOP;

    END;

    Published by: AravindhK on December 6, 2011 13:56

    Do not open cursors when you write

    For  in 
    loop
    
    SQL> Declare
    CURSOR cur IS
    SELECT 1 A FROM dual;
    BEGIN
    IF cur%ISOPEN THEN
    CLOSE cur;
    END IF;
    --OPEN cur;
    DBMS_OUTPUT.PUT_LINE('Cursor opened by for');
    FOR cuv IN cur
    LOOP
    DBMS_OUTPUT.PUT_LINE(cuv.A);
    END LOOP;
    END;
    
    Cursor opened by for
    1
    
    PL/SQL procedure successfully completed.
    
  • Parsing sql - cursor parent and child

    Hi all

    What is the parent and child when parsing sql cursor?

    Thank you

    John

    Well, as Anand mentioned you could yourself. Here's a demo of the workaround based. Based on the change of environment, the sliders would be created and will not be shared that I made using the change of parameter of optimizer_mode. This is done in 11201 with the setting optimizer_features_enable on 10201.

    SQL> drop table t purge;
    
    Table dropped.
    
    SQL> select sql_text from V$sqlarea where sql_text like 'select * from t%';
    
    SQL_TEXT
    --------------------------------------------------------------------------------
    select * from t
    
    SQL> alter system flush shared_pool;
    
    System altered.
    
    SQL> select sql_text from V$sqlarea where sql_text like 'select * from t%';
    
    no rows selected
    
    SQL> save a
    Created file a.sql
    SQL> select * from t;
    select * from t
                  *
    ERROR at line 1:
    ORA-00942: table or view does not exist
    
    SQL> create table t(a char);
    
    Table created.
    
    SQL> select * from t;
    
    no rows selected
    
    SQL> select sql_text from V$sqlarea where sql_text like 'select * from t%';
    
    SQL_TEXT
    --------------------------------------------------------------------------------
    select * from t
    
    SQL> select * from T;
    
    no rows selected
    
    SQL> select sql_text from V$sqlarea where sql_text like 'select * from t%';
    
    SQL_TEXT
    --------------------------------------------------------------------------------
    select * from t
    
    SQL> select sql_text from V$sqlarea where sql_text like 'select * from t%' or sql_text like 'select * from T%';
    
    SQL_TEXT
    --------------------------------------------------------------------------------
    select * from t
    select * from T
    
    SQL> select sql_text,version_count, executions from V$sqlarea where sql_text like 'select * from t%' or sql_text like 'select * from T%';
    
    SQL_TEXT
    --------------------------------------------------------------------------------
    VERSION_COUNT EXECUTIONS
    ------------- ----------
    select * from t
                1          1
    
    select * from T
                1          1
    
    SQL> column sql_text format a40
    SQL> /
    
    SQL_TEXT                                 VERSION_COUNT EXECUTIONS
    ---------------------------------------- ------------- ----------
    select * from t                                      1          1
    select * from T                                      1          1
    
    SQL> select * from T;
    
    no rows selected
    
    SQL> select sql_text from V$sqlarea where sql_text like 'select * from t%' or sql_text like 'select * from T%';
    
    SQL_TEXT
    ----------------------------------------
    select * from t
    select * from T
    
    SQL> select sql_text,version_count, executions from V$sqlarea where sql_text like 'select * from t%' or sql_text like 'select * from T%';
    
    SQL_TEXT                                 VERSION_COUNT EXECUTIONS
    ---------------------------------------- ------------- ----------
    select * from t                                      1          1
    select * from T                                      1          2
    
    SQL> alter session set optimizer_mode=first_rows;
    
    Session altered.
    
    SQL> select * from T;
    
    no rows selected
    
    SQL> select * from t;
    
    no rows selected
    
    SQL> select sql_text,version_count, executions from V$sqlarea where sql_text like 'select * from t%' or sql_text like 'select * from T%';
    
    SQL_TEXT                                 VERSION_COUNT EXECUTIONS
    ---------------------------------------- ------------- ----------
    select * from t                                      1          1
    select * from test_sharing where id=:a               1          3
    select * from test_sharing where id=1                1          0
    select * from test_sharing where id=99               1          0
    select * from T                                      2          3
    
    SQL> select sql_text, child_number, optimizer_mode, plan_hash_value from V$sql where sql_text like 'select * from t%' or sql_text like 'select * fro
    
    SQL_TEXT                                 CHILD_NUMBER OPTIMIZER_ PLAN_HASH_VALUE
    ---------------------------------------- ------------ ---------- ---------------
    select * from t                                     0 FIRST_ROWS      1601196873
    select * from test_sharing where id=:a              0 ALL_ROWS        3492249339
    select * from test_sharing where id=1               0 ALL_ROWS        3492249339
    select * from test_sharing where id=99              0 ALL_ROWS        2354865636
    select * from T                                     0 ALL_ROWS        1601196873
    select * from T                                     1 FIRST_ROWS      1601196873
    
    6 rows selected.
    
    SQL> alter session set optimizer_mode=first_rows_1;
    
    Session altered.
    
    SQL> select * from t;
    
    no rows selected
    
    SQL> select * from T;
    
    no rows selected
    
    SQL> select sql_text, child_number, optimizer_mode, plan_hash_value from V$sql where sql_text like 'select * from t%' or sql_text like 'select * fro
    
    SQL_TEXT                                 CHILD_NUMBER OPTIMIZER_ PLAN_HASH_VALUE
    ---------------------------------------- ------------ ---------- ---------------
    select * from t                                     0 FIRST_ROWS      1601196873
    select * from test_sharing where id=:a              0 ALL_ROWS        3492249339
    select * from test_sharing where id=1               0 ALL_ROWS        3492249339
    select * from test_sharing where id=99              0 ALL_ROWS        2354865636
    select * from T                                     0 ALL_ROWS        1601196873
    select * from T                                     1 FIRST_ROWS      1601196873
    
    6 rows selected.
    
    SQL> alter session set sql_trace=true;
    
    Session altered.
    
    SQL> alter session set optimizer_mode=first_rows_1;
    
    Session altered.
    
    SQL> select * from t;
    
    no rows selected
    
    SQL> select * from T;
    
    no rows selected
    
    SQL> select sql_text,version_count, executions from V$sqlarea where sql_text like 'select * from t%' or sql_text like 'select * from T%';
    
    SQL_TEXT                                 VERSION_COUNT EXECUTIONS
    ---------------------------------------- ------------- ----------
    select * from t                                      2          3
    select * from test_sharing where id=:a               1          3
    select * from test_sharing where id=1                1          0
    select * from test_sharing where id=99               1          0
    select * from T                                      3          5
    
    SQL> select sql_text, child_number, optimizer_mode, plan_hash_value from V$sql where sql_text like 'select * from t%' or sql_text like 'select * fro
    
    SQL_TEXT                                 CHILD_NUMBER OPTIMIZER_ PLAN_HASH_VALUE
    ---------------------------------------- ------------ ---------- ---------------
    select * from t                                     0 FIRST_ROWS      1601196873
    select * from t                                     1 FIRST_ROWS      1601196873
    select * from test_sharing where id=:a              0 ALL_ROWS        3492249339
    select * from test_sharing where id=1               0 ALL_ROWS        3492249339
    select * from test_sharing where id=99              0 ALL_ROWS        2354865636
    select * from T                                     0 ALL_ROWS        1601196873
    select * from T                                     1 FIRST_ROWS      1601196873
    select * from T                                     2 FIRST_ROWS      1601196873
    
    8 rows selected.
    
    SQL> select sql_id,sql_text, child_number, optimizer_mode, plan_hash_value from V$sql where sql_text like 'select * from t%' or sql_text like 'selec
    
    SQL_ID        SQL_TEXT                                 CHILD_NUMBER OPTIMIZER_
    ------------- ---------------------------------------- ------------ ----------
    PLAN_HASH_VALUE
    ---------------
    89km4qj1thh13 select * from t                                     0 FIRST_ROWS
         1601196873
    
    89km4qj1thh13 select * from t                                     1 FIRST_ROWS
         1601196873
    
    7gbgb5nzcdcf3 select * from test_sharing where id=:a              0 ALL_ROWS
         3492249339
    
    SQL_ID        SQL_TEXT                                 CHILD_NUMBER OPTIMIZER_
    ------------- ---------------------------------------- ------------ ----------
    PLAN_HASH_VALUE
    ---------------
    0890tcnrf5jsv select * from test_sharing where id=1               0 ALL_ROWS
         3492249339
    
    7hg3cujy0ya0r select * from test_sharing where id=99              0 ALL_ROWS
         2354865636
    
    ahgbnyrbh7bp1 select * from T                                     0 ALL_ROWS
         1601196873
    
    SQL_ID        SQL_TEXT                                 CHILD_NUMBER OPTIMIZER_
    ------------- ---------------------------------------- ------------ ----------
    PLAN_HASH_VALUE
    ---------------
    ahgbnyrbh7bp1 select * from T                                     1 FIRST_ROWS
         1601196873
    
    ahgbnyrbh7bp1 select * from T                                     2 FIRST_ROWS
         1601196873
    
    8 rows selected.
    
    SQL> set pagesize 9999
    SQL> /
    
    SQL_ID        SQL_TEXT                                 CHILD_NUMBER OPTIMIZER_
    ------------- ---------------------------------------- ------------ ----------
    PLAN_HASH_VALUE
    ---------------
    89km4qj1thh13 select * from t                                     0 FIRST_ROWS
         1601196873
    
    89km4qj1thh13 select * from t                                     1 FIRST_ROWS
         1601196873
    
    7gbgb5nzcdcf3 select * from test_sharing where id=:a              0 ALL_ROWS
         3492249339
    
    0890tcnrf5jsv select * from test_sharing where id=1               0 ALL_ROWS
         3492249339
    
    7hg3cujy0ya0r select * from test_sharing where id=99              0 ALL_ROWS
         2354865636
    
    ahgbnyrbh7bp1 select * from T                                     0 ALL_ROWS
         1601196873
    
    ahgbnyrbh7bp1 select * from T                                     1 FIRST_ROWS
         1601196873
    
    ahgbnyrbh7bp1 select * from T                                     2 FIRST_ROWS
         1601196873
    
    8 rows selected.
    
    SQL> set linesize 200
    SQL> /
    
    SQL_ID        SQL_TEXT                                 CHILD_NUMBER OPTIMIZER_ PLAN_HASH_VALUE
    ------------- ---------------------------------------- ------------ ---------- ---------------
    89km4qj1thh13 select * from t                                     0 FIRST_ROWS      1601196873
    89km4qj1thh13 select * from t                                     1 FIRST_ROWS      1601196873
    7gbgb5nzcdcf3 select * from test_sharing where id=:a              0 ALL_ROWS        3492249339
    0890tcnrf5jsv select * from test_sharing where id=1               0 ALL_ROWS        3492249339
    7hg3cujy0ya0r select * from test_sharing where id=99              0 ALL_ROWS        2354865636
    ahgbnyrbh7bp1 select * from T                                     0 ALL_ROWS        1601196873
    ahgbnyrbh7bp1 select * from T                                     1 FIRST_ROWS      1601196873
    ahgbnyrbh7bp1 select * from T                                     2 FIRST_ROWS      1601196873
    
    8 rows selected.
    
    SQL> select child_number, child_address, stats_row_mismatch, optimizer_mode_mismatch
      2  from v$sql_shared_cursor where sql_id='ahgbnyrbh7bp1';
    
    CHILD_NUMBER CHILD_AD S O
    ------------ -------- - -
               0 1A610050 N N
               1 1F148DA4 N Y
               2 1A630C90 Y N
    
    SQL>
    

    You can see an inconsistency in the optimizer_mode resulting in another creation of child cursor. You can try to use the parameter cursor_sharing similar value and bind variables that would also cause child several sliders to create. For the view V$ sql_shared_cursor, check the docs.

    HTH
    Aman...

    PS: Please don't bump up to the thread. This is not support so people are not forced to update immediately. All are volunteers so assume that they would update the thread as and when they have / get time to do.

  • REF cursor in sql dynamic help to run immediately

    Hello

    How can we get the Ref cursor out a dynamic sql statement by executing immediate proceedings
    for example, immediately run ' open CROR for select * from dynamicTable'

    in this area, CROR is a dynamic cursor and table name is dynamic (known at run time), and we can't write static sql statement.

    Thank you

    I don't know what exactly you are after but here is a sample of what can be done.

    SQL> VAR r REFCURSOR;
    SQL> BEGIN
      2          OPEN :r FOR 'SELECT * FROM DUAL';
      3  END;
      4  /
    
    PL/SQL procedure successfully completed.
    
    SQL> PRINT r
    
    D
    -
    X
    

    You can use the OPEN... FOR education with a dynamic string.

  • The adaptation and Pl/SQL cursor sharing

    Hello

    I have this database:

    NLSRTL11.2.0.1.0Production
    Oracle Database 11g Enterprise Edition11.2.0.1.064 bit Production
    PL/SQL11.2.0.1.0Production
    AMT for Solaris:11.2.0.1.0Production

    I'm testing the queries and adaptive cursor sharing. I have a table T1 that is created by selecting all object. It has additional is NOT NULL ID of the column that is PK and is filled through sequence. It has a regular index (OBJECT_TYPE, OBJECT_NAME). Statistics are collected on the T1 table and its indexes.

    Total of T1 lines and are 1065951.

    I have run this test in SqlPlus:

    ID of the VARIABLE NUMBER;

    EXECUTE: id: = 10;

    SELECT COUNT (*) FROM t1 WHERE id <: id;

    So I check the instruction in v$ sql and the execution plan and I can see that the plan is:

    SQL_ID, 3m2qaytqgk9jt, number of children 0

    -------------------------------------

    Select COUNT (*) from t1 where id <: id

    Hash value of plan: 212448250

    ---------------------------------------------------------------------------

    | ID | Operation | Name | Lines | Bytes | Cost (% CPU). Time |

    ---------------------------------------------------------------------------

    |   0 | SELECT STATEMENT |       |       |       |   193 (100) |          |

    |   1.  GLOBAL TRI |       |     1.     6.            |          |

    |*  2 |   INDEX RANGE SCAN | PK_T1 | 99999.   585K |   193 (1) | 00:00:03 |

    ---------------------------------------------------------------------------

    Information of predicates (identified by the operation identity card):

    ---------------------------------------------------

    2 - access("ID"<:ID))

    Second test:

    ID of the VARIABLE NUMBER;

    EXECUTE: id: = 1000000.

    SELECT COUNT (*) FROM t1 WHERE id <: id;

    Execution plan:

    SQL_ID, 3m2qaytqgk9jt, number of children 1

    -------------------------------------

    Select COUNT (*) from t1 where id <: id

    Hash value of plan: 1953966236

    -------------------------------------------------------------------------------

    | ID | Operation | Name | Lines | Bytes | Cost (% CPU). Time |

    -------------------------------------------------------------------------------

    |   0 | SELECT STATEMENT |       |       |       |   559 (100) |          |

    |   1.  GLOBAL TRI |       |     1.     6.            |          |

    |*  2 |   FULL RESTRICTED INDEX SCAN FAST | PK_T1 |  1000K |  5859K |   559 (2) | 00:00:07 |

    -------------------------------------------------------------------------------

    Information of predicates (identified by the operation identity card):

    ---------------------------------------------------

    2 - filter("ID"<:ID))

    Output:

    SQL > SELECT sql_id, child_number, executions, 'IS_BIND_SENSITIVE', 'IS_BIND_AWARE', 'IS_SHAREABLE' OF V$ SQL WHERE SQL_ID = "3m2qaytqgk9jt";

    THE EXECUTIONS OF CHILD_NUMBER SQL_ID I I I

    ------------- ------------ ---------- - - -

    3m2qaytqgk9jt 0 2 O N N

    1 3 3m2qaytqgk9jt Y Y Y

    As we can see it Adaptive cursor sharing has been used and in both cases the appropriate execution plan has been used.

    When I run test with PL/SQL block, however, I don't see the use of extended cursor sharing. Could you please help understand why?

    The test is (I used deliberately < = in order to create the new parent cursor):

    DECLARE

    PID NUMBER;

    CNT PLS_INTEGER;

    BEGIN

    BECAUSE me in 1... 10 LOOP

    IF i IN (2, 4, 6, 10) THEN

    PID: = round (dbms_random.value (1, 5000));

    ON THE OTHER

    PID: = round ((100000, 1600000) dbms_random.value);

    END IF;

    dbms_output.put_line ('ID: ' | pid);

    COUNT (*) of SELECT INTO cnt FROM t1 WHERE id < = pid;

    END LOOP;

    END;

    /

    Output of this is:

    ID: 396582

    ID: 2584

    ID: 560405

    ID: 3275

    ID: 827442

    ID: 4515

    ID: 167771

    ID: 652411

    ID: 512147

    ID: 230

    As we can see some ID values are good candidates for INDEX BEACH, others are for the INDEX FAST FULL SCAN. However, I am only a child cursor for my parents:

    SQL > SELECT sql_id, child_number, executions, 'IS_BIND_SENSITIVE', 'IS_BIND_AWARE', 'IS_SHAREABLE' OF V$ SQL WHERE SQL_ID = "6xh03mm87nmu3";

    THE EXECUTIONS OF CHILD_NUMBER SQL_ID I I I

    ------------- ------------ ---------- - - -

    0 10 6xh03mm87nmu3 Y N Y

    SQL >

    Please pay attention to the value for IS_BIND_AWARE, who is with my first child 0. So no other children were created. Why in PL/SQL, it behaves differently and how can we enjoy the cursor of adaptation in this context?

    Thank you!

    My immediate thoughts were under cover PLSQL optimizations.

    PLSQL_OPTIMIZE_LEVEL has no effect.

    To run I had to Board BIND_AWARE and SESSION_CACHED_CURSORS value 0.

    Subsequently found Randolf Geist post in the same direction:

    Oracle related stuff: Adaptive Cursor Sharing

  • PL/SQL cursors: definition and purpose

    How are you?

    I wanted to ask the following question:
    What is the exact definition of a "slider"? of course, it is not equivalent to a pointer in C/C++.

    also, why can not simply RETRIEVE us the data in a RECORD without a slider? in other words, what is the point of a 'slider '?

    Obviously, there is a specific purpose of cursors in PL/SQL language, I just wanted to know what it is. The book that I use does not explain the two issues I have just raised.


    Thank you :)

    In PL/SQL, generally, using variables, you would store stores unique values and can be used for processing later. You would use a SELECT - CLAUSE to extract the required of the database value and store it in your variable. If the SELECT query is extraction of several columns, you would use a different variable for each column name.

    But what to do when your SELECT query returns many rows? And your need is to treat each line in a loop one after the other?

    One solution is to use the sliders (are there others too). Cursors provide a way by which you can run a query that returns multiple records and then loop through the cursor to treat each one record after another.

    In addition, if you worked on any application front end (say J2EE), also would you use cursors (called REFCURSORs in this case) to return the result of the whole (including multiple records) request as a result set. The calling (in this case - a DAO) program loops through the ResultSet and treats each unique record sequentially.

    Personally, I use the sliders in another case - even when the query returns a single row. If I have to go get a big no. (even if only a row) columns in my SELECT query, then I go for a CURSOR, instead of declaring each individual value. In this way, I avoid all of these statements and my code is as compact as it can get. Here's how to use it...

    Report separately the individual values

    declare
       l_val1  my_table.val1%type;
       l_val2  my_table.val2%type;
       l_val3  my_table.val3%type;
       ...
       l_valn  my_table.valn%type;
    
    begin
    ...
       select val1, val2, val3, ... valn
       into   l_val1, l_val2, l_val3, ... l_valn
       from   my_table
       where  <>;
    
       if ((val1 = val2) or (val3 = val4))
       then
          ...
       end if;
    end;
    

    And it's the same thing with the CURSOR

    declare
       cursor l_cur is
          select val1, val2, val3, ... valn
          from   my_table
          where  <>;
    begin
       for rec in l_cur
       loop
          if ((rec.val1 = rec.val2) or (rec.val3 = rec.valn)
          then
             ...
          end if;
       end loop;
    end;
    

    You would see that even in this demo, I saved 5 lines!

    I hope this helps!
    -Shreyas.

  • SQL Query help find albums from sale

    Hi Experts,

    I have the following data and the need to find the book Top sold in each type.

    Book Type QTY

    20Help the3
    10Kitchen1
    5Navigation2
    30Help the4

    Please let me how can know we get this simple SQL help?

    Thank you

    Bharat

    Hello

    Bharat Hegde wrote:

    Hi all

    I tried to use Dense_rank as below. But it gives me the top selling books. I need high library in each type...

    This looks like a job for 'PARTITION BY type

    For example:

    WITH got_rnk AS

    (

    SELECT b.bid, b.type

    SUM (o.quantity) AS total_quantity

    DENSE_RANK () OVER ( PARTITION BY b.type

    ORDER OF SUM (o.quantity) / / DESC

    ) AS rnk

    B BOOK

    o order1

    WHERE b.bid = o.bid

    GROUP BY b.bid, b.type

    )

    SELECT total_quantity, type submission

    OF got_rnk

    WHERE rnk = 1

    ;

    . Aggregate functions (such as the SUM, above) are calculated before analytical functions, so an analytic function (such as DENSE_RANK above) may depend on an aggregate function; you don't need a separate subquery for that.

  • SQL query - help with join

    Dear friends,

    Version of DB - 11.1.0.7... , I'm stuck with SQL basics today... need your help...

    The slot SQL tells me "cache them locks library" in the database that I will put up as a proactive measure.

    I'll be it works via shell script and include the table gv instance_name $ instance ... I'm a little confused as to how a 3rd table "gv$ instance ' can be introduced into the query in order to make the instance_name in the result set...

    SELECT * FROM)

    SELECT / * + LEADING (a) USE_HASH (u) * /.

    instance_name, INST_ID select, blocking_inst_id, blocking_session, username, session_id, sql_id, current_obj #,.

    DECODE (sql_opcode, 1, 'CREATE TABLE', 2, 'INSERT') as "order."

    Event, mod(P1,16) p1, p2, p3

    COUNT (*) totalseconds

    , SUM (CASE WHEN wait_class = 'Application' THEN 1 ELSE 0 END) 'Application '.

    Of

    (SELECT

    a.*

    , TO_CHAR (CASE WHEN session_state = 'WAITING' THEN ELSE null END p1, '0XXXXXXXXXXXXXXX') p1hex

    , TO_CHAR (CASE WHEN session_state = "PENDING" THEN p2 ELSE null END, '0XXXXXXXXXXXXXXX') p2hex

    , TO_CHAR (CASE WHEN session_state = "PENDING" THEN ELSE null END p3, '0XXXXXXXXXXXXXXX') p3hex

    SGS $ active_session_history one) a

    u dba_users

    WHERE

    a.user_id = u.user_id

    AND sample_time BETWEEN sysdate-90 /(24*60) AND sysdate

    - AND a test of ('library cache lock', 'library cache pin")

    AND event like '% library '.

    GROUP BY

    INST_ID select, blocking_inst_id, blocking_session, username, session_id, sql_id, current_obj #,.

    DECODE (sql_opcode, 1, 'CREATE TABLE', 'INSERT', 2),

    event, mod (p1, 16), p2, p3

    Having count (*) > 5

    ORDER BY

    TotalSeconds DESC

    , INST_ID select, blocking_session, username, session_id, sql_id, current_obj #, 'Order', event

    )

    WHERE

    ROWNUM < = 20

    /

    replace

    instance_name

    by

    (select instance_name gv$ instance where INST_ID select = a.inst_id) instance_name

    or select... in... a, u, gv$ instance where... and gv$ instance.inst_id (+) = a.inst_id...

  • PL SQL cursor is not over.

    Hello

    Here is the code for my procedure

    CREATE OR REPLACE PROCEDURE DEV_CREATE_CONTRACT
    IS
       CURSOR C_CONTRACT
       IS
        select emp_no, person_id, contract_start, contract_end ,
        round((contract_end - contract_start)/365)duration,  'Y' Duration_units,
        employee_salary,'SPECIFIED_PERIOD' type,'C-COMPLETED' status , EMP_NO||' - '||CON_SEQNO REFERENCE
        from emp_con_type a,per_people_f b
        where to_char(a.emp_no) =b.employee_number
        and sysdate between effective_start_date and effective_end_date
        and emp_no not in 
    (
    '124744491',
    '1223816',
    '938201',
    '1082809',
    '1092607',
    '867712'
    );
       LC_C_CONTRACT             C_CONTRACT%ROWTYPE;
       L_CONTRACT_ID             NUMBER;
       --L_EFFECTIVE_START_DATE    DATE;
       --L_EFFECTIVE_END_DATE      DATE;
       L_OBJECT_VERSION_NUMBER   NUMBER;
       ERROR_DESC                VARCHAR2 (240);
       --LV_CONTRACT_FLAG          CHAR (1);
     --  L_SEQ                     VARCHAR2 (20);
       eff_date                 date;
    BEGIN
       OPEN C_CONTRACT;
       LOOP
          FETCH C_CONTRACT
           INTO LC_C_CONTRACT;
          EXIT WHEN C_CONTRACT%NOTFOUND;
          BEGIN
          select effective_start_date into eff_date 
          from per_assignments_f
          where person_id =lc_c_contract.person_id;
             HR_CONTRACT_API.CREATE_CONTRACT
                              (P_VALIDATE                   => FALSE,
                               P_EFFECTIVE_DATE             => eff_date,
                               P_PERSON_ID                  => LC_C_CONTRACT.PERSON_ID,
                               P_REFERENCE                  => seq_per_contracts.nextval,
                               P_TYPE                       => LC_C_CONTRACT.TYPE,
                               P_STATUS                     => LC_C_CONTRACT.STATUS,
                               P_DURATION                   => LC_C_CONTRACT.DURATION,
                               P_DURATION_UNITS             => LC_C_CONTRACT.DURATION_UNITS,
                               P_CONTRACT_ID                => L_CONTRACT_ID,
                               P_EFFECTIVE_START_DATE       => LC_C_CONTRACT.contract_start,
                               P_EFFECTIVE_END_DATE         => LC_C_CONTRACT.contract_end,
                               P_OBJECT_VERSION_NUMBER      => L_OBJECT_VERSION_NUMBER
                              );
            rollback;
    --        DBMS_OUTPUT.PUT_LINE ('CONTRACT ID    : ' || L_CONTRACT_ID);
            UPDATE emp_con_type  SET ERR_DESC =L_CONTRACT_ID
            WHERE  EMP_NO=LC_C_CONTRACT.emp_no;
            commit;
          /*EXCEPTION
             WHEN OTHERS
             THEN      
                DBMS_OUTPUT.PUT_LINE (SQLERRM);*/
       --    COMMIT;      
          /*L_CONTRACT_ID := '';
          L_OBJECT_VERSION_NUMBER := '';
          L_EFFECTIVE_START_DATE := '';
          L_EFFECTIVE_END_DATE := '';
          ERROR_DESC := '';
          LV_CONTRACT_FLAG := '';*/
          EXCEPTION
             WHEN OTHERS
             THEN          
                ERROR_DESC := ERROR_DESC || SQLERRM;
                --            UPDATE DEV_CONTRACT
                --               SET JOB_ERROR_DESCRIPTION = ERROR_DESC,
                --                   JOB_PROCESS_FLAG = LV_CONTRACT_FLAG
                --             WHERE LINE_ID = LC_C_CONTRACT.LINE_ID;
                --DBMS_OUTPUT.PUT_LINE (SQLERRM);
          END;    
             END LOOP;
       CLOSE C_CONTRACT;
    EXCEPTION
       WHEN OTHERS
       THEN
       null;
          --DBMS_OUTPUT.PUT_LINE (SQLERRM);
    END;
    /
    

    The SQL statement for the cursor returns, lines of 1224, but only 154 lines are updated in the table that is updated in the LOOP. I don't know what could be the reason... This loop should be executed 1224 times but its executed only 154 times...

    No idea what could be the reason?

    > No idea what could be the reason?

    WHEN other hides the failure.

    remove, remove & eliminate all code exception

    Why why check these links.

    http://tkyte.blogspot.com/2007/03/dreaded-others-then-null-strikes-again.html

    http://tkyte.blogspot.com/2008/01/why-do-people-do-this.html

    http://tkyte.blogspot.com/2007/03/challenge.html

  • text of the position cursor help

    Ok. When I try to use the text tool, the cursor is STILL stuck horizontal face, like this:---(faire semblant c'est une sur le côté j'ai). I want to face vertically again like it used to, like this: I. Help. Have scoured internet everywhere and I'm so frustrated.

    Have you tried trashing the prefs? See replace your preferences

  • Smaller than the actual brush, PS CC 2015 (brush and eraser) cursor help!

    PC specs and hardware:

    Windows 8, Photoshop CC 2015, Creative Cloud 2015, Intuos 3 tablet, 1920 x 1080 display

    I've updated for Creative just a couple of hours there are clouds and have been satisfied with the frustrations without end.

    Most of the questions I resolved or can live with, but is not one of these.

    Untitled-2.png

    In my image, the circle at the bottom has a selection rectangle (which is supposed to be my brush cursor, but when I screen cap it disappears) indicating the size of the cursor, but the cleared area is significantly greater than the slider. I messed up round in 'Sliders' options, but none of those who have had no effect.Untitled-.png

    I'll try to be as helpful as possible as well as to answer the questions.

    (In addition, tips to make my windows not as big tool?) I have messed with the user interface in the menu options, but that is all fucked up too.)

    Size slider should show the range including any flag.

    Your screenshot is 1920 x 1080, but for some reason it looks like it has triggered the IU 200%.  Is it perhaps a little notebook?  Set it to 100% like below, and you will have more space, but obviously with more small fonts and icons

  • SQL - select Help - box When? Return value of the second Table?

    -Next to people on this forum I am probably somewhere between a beginner and an intermediate SQL user.

    Ive been using a case when stated in plsql to find "all who has status in any program was canceled during a specific time, but have become or are still active in another program"

    So, Im actually trying to return a value from another table in a case where, but this isn't anthing taste other than a text declared as 'Yes' or 'no '.

    This is the select statement - y at - it another way to do it where I can get the results I need?

    -case when pp.party_id in (select pp1.party_id - cancelled active clients in another program)

    of asa.program_participation pp1,.

    ASA.curr_prog_participation_status cpps1

    where pp1.program_participation_id = cpps1.program_participation_id

    and pp1.party_id = pp.party_id

    and cpps1.code_value = 'Act')

    So 'Yes' is still 'No' end as Active_in_Other_Prg

    So - instead of 'Yes', I want essentially the program they are active or pp1.program_id, another null

    It is possible that the client can be active in more than one program as well.

    Any help is greatly appreciated, I explored with if and decodes but I can't get anything to work.

    Ben

    Looks like an outer join. See doc ora: joins at

    Select p

    q.party_id

    q.program_id

    of table_with_party_id p

    , (select pp1.party_id - cancelled active clients in another program)

    pp1.program_id

    of asa.program_participation pp1,.

    ASA.curr_prog_participation_status cpps1

    where pp1.program_participation_id = cpps1.program_participation_id

    and pp1.party_id = pp.party_id

    and cpps1.code_value = 'ACT') q

    where p.party_id = q.party_id (+)

    Note: In the example above shoudn't it be a space between the (and +), but the forum software automatically converts to

    The outer join will connect display all records in the table p and q records only if fits the party_id, IE q.party_id and q.program_id will be null if there is no match.

    Edit: adding program_id

  • PL/SQL cursor loop... error IN the necessary clause... but several lines

    Oracle 11 g 2 Linux x86_64

    Hi all


    I do turn the PL/SQL block below, but get the error below. I know, the INTO clause can be used only when a single line will be returned. In this case, I know that it returns multiple lines, so why he asked to use the INTO clause?

    DECLARE

    v_object VARCHAR2 (10): = "TABLE";

    v_schema VARCHAR2 (30): = 'TEST ';

    CURSOR tblsze_cur IS

    SELECT table_name

    FROM dba_tables

    Owner WHERE = 'TEST '.

    AND (IN) table_name

    "T1"

    "T2."

    "T3");

    BEGIN

    FOR tbl_rec IN tblsze_cur

    LOOP

    Select * from

    Table (dbms_space. OBJECT_GROWTH_TREND

    (v_schema, tbl_rec.table_name, v_object)) ;

    END LOOP;

    END;

    /

    Select * from table (dbms_space. OBJECT_GROWTH_TREND

    *

    ERROR at line 21:

    ORA-06550: line 21, column 3:

    PLS-00428: an INTO clause in this SELECT statement

    It would be something more like this (untested)...

    Set serverout on

    create type object_growth_trend_row as object)
    validating TIMESTAMP,
    space_usage NUMBER,
    space_alloc NUMBER,
    quality VARCHAR (20))
    /

    Create type object_growth_trend_table as table of the object_growth_trend_row
    /

    DECLARE
    number of r;
    We varchar2 (30): = 'SCOTT ';
    TYPE nmtbl IS TABLE OF THE all_tables.table_name%TYPE;
    tNom nmtbl;
    tgrowth object_growth_trend_table;
    CURSOR c1 IS
    SELECT table_name
    From all_tables
    Owner WHERE we =
    AND table_name in ('EMP', 'Department');
    growth of cursor (tablename in varchar2) is
    Select *.
    table (dbms_space.object_growth_trend (tablename, 'TABLE'));
    BEGIN
    OPEN c1;
    FETCH c1 COLLECT LOOSE tNom;
    CLOSE c1;
    BECAUSE me IN tNom. FIRST... tNom. LAST
    LOOP
    r: = 0;
    dbms_output.put_line (' growth for table: ' | tname (i));
    FOR g IN growth (tname (i))
    LOOP
    r: = r + 1;
    dbms_output.put_line ('Timestamp: ' | g.timePoint |') Use: ' | g.space_usage);
    END LOOP;
    DBMS_OUTPUT. Put_line (' found lines: ' | r);
    END LOOP;
    END;
    /

    I just tested this in my SYS schema (although you should not create objects in SYS.)  and got...

    For table growth: EMP

    EXCEPTION in the treatment of the Charles - code:-14551 msg: ORA-14551: cannot perform a DML operation inside a query

    Timestamp: 3 July 13 09.15.27.250000 use: 5332

    Found lines: 1

    For table growth: DEPT

    EXCEPTION in the treatment of the Charles - code:-14551 msg: ORA-14551: cannot perform a DML operation inside a query

    Timestamp: 3 July 13 09.15.27.282000 use: 4846

    Found lines: 1

    Not sure why it's up the DML operation... which seems inner exception to the dbms_space package.  Even if I just run it directly in sys like this:

    SQL > SELECT *.
    2. IN the TABLE (dbms_space.object_growth_trend ('SYS', ' $', TAB 'TABLE'));

    AFTER SPACE_USAGE SPACE_ALLOC QUALITY
    --------------------------------------------------------------------------- ----------- ----------- --------------------
    3 JULY 13 09.19.01.956000 10342201 24117248 INTERPOLATED


    4 JULY 13 09.19.01.956000 10342201 24117248 INTERPOLATED
    JULY 5, 13 09.19.01.956000 10342201 24117248 INTERPOLATED
    6 JULY 13 09.19.01.956000 10342201 24117248 INTERPOLATED
    7 JULY 13 09.19.01.956000 10342201 24117248 INTERPOLATED
    8 JULY 13 09.19.01.956000 10342201 24117248 INTERPOLATED
    9 JULY 13 09.19.01.956000 10342201 24117248 INTERPOLATED
    10 JULY 13 09.19.01.956000 10342201 24117248 INTERPOLATED
    JULY 11, 13 09.19.01.956000 10342201 24117248 INTERPOLATED
    12 JULY 13 09.19.01.956000 10342201 24117248 INTERPOLATED
    13 JULY 13 09.19.01.956000 10342201 24117248 INTERPOLATED
    14 JULY 13 09.19.01.956000 10342201 24117248 INTERPOLATED
    15 JULY 13 09.19.01.956000 10342201 24117248 INTERPOLATED
    16 JULY 13 09.19.01.956000 10342201 24117248 INTERPOLATED
    17 JULY 13 09.19.01.956000 10342201 24117248 INTERPOLATED
    18 JULY 13 09.19.01.956000 10342201 24117248 INTERPOLATED
    19 JULY 13 09.19.01.956000 10342201 24117248 INTERPOLATED
    20 JULY 13 09.19.01.956000 10342201 24117248 INTERPOLATED
    21 JULY 13 09.19.01.956000 10342201 24117248 INTERPOLATED
    22 JULY 13 09.19.01.956000 10342201 24117248 INTERPOLATED
    23 JULY 13 09.19.01.956000 10342201 24117248 INTERPOLATED
    24 JULY 13 09.19.01.956000 10342201 24117248 INTERPOLATED
    25 JULY 13 09.19.01.956000 10342201 24117248 INTERPOLATED
    26 JULY 13 09.19.01.956000 10342201 24117248 GOOD
    27 JULY 13 09.19.01.956000 10342201 24117248 GOOD
    28 JULY 13 09.19.01.956000 10342201 24117248 GOOD
    29 JULY 13 09.19.01.956000 10342201 24117248 GOOD
    30 JULY 13 09.19.01.956000 10342201 24117248 GOOD
    31 JULY 13 09.19.01.956000 10342201 24117248 GOOD
    1ST AUGUST 13 09.19.01.956000 10342201 24117248 GOOD
    2 AUGUST 13 09.19.01.956000 10342201 24117248 GOOD
    3 AUGUST 13 09.19.01.956000 10342201 24117248 PLANNED
    4 AUGUST 13 09.19.01.956000 10342201 24117248 PLANNED
    5 AUGUST 13 09.19.01.956000 10342201 24117248 PLANNED
    6 AUGUST 13 09.19.01.956000 10342201 24117248 PLANNED
    7 AUGUST 13 09.19.01.956000 10342201 24117248 PLANNED

    36 selected lines.

    EXCEPTION in the treatment of the Charles - code:-14551 msg: ORA-14551: cannot perform a DML operation inside a query

    ... She still throws the exception.

    Doesn't seem like a package of well designed if the types are provided only in the package and not as objects of database, which are required to be used in SQL based in pipeline.

  • SQL cursor problem

    Hi all

    I want to see the records in the table emp or a message if the emp table is empty, but under cursor shows the two,

    How can I solve this problem, please help.

    declare
    cursor emp_cur is
    Select * from emp;
    SheikYerbouti emp % rowtype;
    Start
    Open emp_cur;
    loop
    extract in SheikYerbouti emp_cur;
    If emp_cur % notfound then
    dbms_output.put_line ('there no record in the employee table');
    "exit";
    on the other
    dbms_output.put_line (emp_rec.empno |) » '|| emp_rec.ename);
    end if;
    end loop;
    close emp_cur;
    end;

    You should do something like this,

    not tested.

    DECLARE
       CURSOR emp_cur
       IS
          SELECT * FROM emp;
    
       emp_rec   emp%ROWTYPE;
       i         NUMBER := 0;
    BEGIN
    
       IF emp_cur%ISOPEN THEN
    
          CLOSE emp_cur;
    
       END IF;
    
       OPEN emp_cur;
    
       LOOP
    
          FETCH emp_cur INTO emp_rec;
    
          EXIT WHEN emp_cur%NOTFOUND;
    
          i     := i + 1;
    
          DBMS_OUTPUT.PUT_LINE (emp_rec.empno || ' ' || emp_rec.ename);
    
       END LOOP;
    
       IF i = 0 THEN
          DBMS_OUTPUT.PUT_LINE ('There is no record in employee table ');
       END IF;
    
       CLOSE emp_cur;
    
    END;
    

    Earlier you were printing that the records did not exist for when the extraction fails. Extraction fails at the end of the recording for any cursor. If you have found the two.
    Now, you print it out only if message I = 0, which means that the cursor did not return a single record.

    G.

Maybe you are looking for