Home Database Oracle what is oracle cursor

what is oracle cursor

Feb 23, 2022 am 11:35 AM
oracle cursor

In Oracle, a cursor is a mechanism that uses the keyword CURSOR to define a set of data sets queried by Oracle. The queried data set can be stored in memory, and then the cursor points to one of the data sets. Record, through the loop cursor to achieve the purpose of looping the data set.

what is oracle cursor

The operating environment of this tutorial: Windows 7 system, Oracle 11g version, Dell G3 computer.

In Oracle, cursors are a mechanism by which a name can be assigned to a SELECT statement and the information in that SQL statement can be processed.

Oracle cursor defines a set of data sets queried by Oracle through the keyword CURSOR. Similar to an array, the queried data set is stored in the memory, and then the cursor points to one of the records, and the cursor is looped Achieve the purpose of looping the data set.

What is the function of cursor?

①Specify the position of a specific row in the result set.

②Retrieve one row or several consecutive rows based on the current result set position.

③ Modify the data in the row at the current position of the result set.

④ Define different sensitivity levels for data changes made by other users.

⑤The database can be accessed programmatically.

Type of Oracle cursor?

1. Static cursor: A cursor whose result set has been confirmed (statically defined). Divided into implicit and explicit cursors

  • Implicit cursor: All DML statements are implicit cursors, and SQL statement information can be obtained through the implicit cursor attribute.

  • Display cursor: The user displays the declared cursor, that is, the specified result set. When a query returns more than one row of results, an explicit cursor is required.

2. REF cursor: a temporary object that dynamically associates the result set.

What are the statuses of Oracle cursors and how to use cursor attributes?

①The status of the cursor is represented by attributes.

  • %Found: The execution status of Fetch statement (getting records) is True or False.

  • %NotFound: Whether the last record is extracted as True or False.

  • %ISOpen: Whether the cursor is open True or False.

  • %RowCount: The number of rows currently extracted by the cursor.

②Use the properties of the cursor.

Example:

/* conn scott/tiger */
  Begin
   Update emp Set  SAL = SAL + 0.1  Where JOB = 'CLERK';
   If  SQL%Found  Then
    DBMS_OUTPUT.PUT_LINE('已经更新!');
   Else
    DBMS_OUTPUT.PUT_LINE('更新失败!');
   End  If;
  End;
Copy after login

How to use the display cursor? How to iterate over a loop cursor?

1. Use the display cursor

  • Declare the cursor: divide the storage area. Note that the Select statement is not executed at this time.

CURSOR 游标名( 参数 列表)   [返回值类型]   IS   Select 语句;
Copy after login
  • Open the cursor: execute the Select statement, obtain the result set and store it in the cursor. At this time, the cursor points to the head of the result set, not the first record.

 Open 游标名( 参数 列表);
Copy after login
  • Get records: Move the cursor to get a record

Fetch  游标名InTo  临时记录或属性类型变量;
Copy after login
  • Close the cursor: The cursor is placed in the buffer pool and the resources are not completely released. Can be reopened.

Close  游标名;
Copy after login

2. Traversing the loop cursor

  • For loop cursor

The loop cursor is implicitly opened The cursor automatically scrolls to obtain a record and automatically creates a temporary record type variable to store the record. The cursor is automatically closed after processing.

     For  变量名  In  游标名 
     Loop
      数据处理语句;
     End Loop;
Copy after login
  • Loop cursor

     。。。
    Loop
     Fatch  游标名InTo  临时记录或属性类型变量;
     Exit  When   游标名%NotFound;
    End   Loop;
     。。。
Copy after login

Example 1:

/* conn scott/tiger */
   Declare
     Cursor myCur is select empno,ename,sal from emp;
     vna varchar2(10);
     vno number(4);
     vsal number(7,2);
  Begin
     open myCur;
     fetch myCur into vno,vna,vsal;
     dbms_output.put_line(vno||'    '||vna||'    '||vsal);
     close myCur;
  End;
  /
Copy after login

Example 2: Use loop to traverse the cursor.

 /* conn scott/tiger */
  Declare
     Cursor myCur is select ename,job,sal,empno from emp;
     varE myCur%rowType;
  Begin
     if myCur%isopen = false then
        open myCur;
       dbms_output.put_line('Opening...');
     end if;
     loop
        fetch myCur into varE;
        exit when myCur%notfound;
        dbms_output.put_line(myCur%rowCount||'    '||vare.empno||'    '||vare.ename||'    '||vare.sal);
     end loop;
     if myCur%isopen then
        Close myCur;
        dbms_output.put_line('Closing...');
     end if;
  End;
  /
Copy after login

Example 3: Using a For loop to traverse the cursor,

  /* conn scott/tiger */
  Declare
     Cursor myCur is select * from emp;
  Begin
     for varA in myCur
      loop
         dbms_output.put_line(myCur%rowCount||'    '||varA.empno||'    '||varA.ename||'  '||varA.sal);
      end loop;
  End;
  /
Copy after login

How to update and delete records in the displayed cursor?

①The WHERE CURRENT OF substring in the UPDATE or DELETE statement specifically handles the most recent data retrieved from the table to be performed UPDATE or DELETE operations.

To use this method, you must use the FOR UPDATE substring when declaring the cursor. When the dialog uses the FOR UPDATE substring to open a cursor,

All data rows in the return set will be in the row Level (ROW-LEVEL) exclusive locking, other objects can only query these data rows,

cannot perform UPDATE, DELETE or SELECT...FOR UPDATE operations.

In a multi-table query, use the OF clause to lock a specific table. If the OF clause is ignored, the selected data rows in all tables will be locked.

If these data rows have been locked by other sessions, then under normal circumstances ORACLE will wait until the data rows are unlocked.

② Use update or delete:

⑴ Declare to update or delete the display cursor:

   Cursor 游标名IS  SELECT 语句   For Update [ Of  更新列列名];
   Cursor 游标名IS  SELECT 语句   For Delete [ Of  更新列列名];
Copy after login

⑵ Use the display cursor to update or delete the current record:

   Update  表名   SET   更新语句  Where   Current  Of   游标名;
   Delete  From  表名   Where   Current  Of   游标名;
Copy after login

Example 1: Update the display cursor record

   /*conn scott/tiger*/
   Declare
     Cursor myCur is select job from emp for update;
       vjob empa.job%type;
       rsal empa.sal%type;
    Begin
       open myCur;
       loop
          fetch myCur into vjob;
          exit when myCur%notFound;
          case  (vjob)
             when 'ANALYST' then  rsal := 0.1;
            when  'CLERK' then  rsal := 0.2;
             when  'MANAGER' then  rsal := 0.3;
             else
               rsal := 0.5;
          end case;
        update emp set sal = sal + rsal where current of myCur;
       end loop;
    End;
    /
Copy after login

Example 2: Delete the display cursor record

    /*conn scott/tiger
    Crate table  empa  Select * from scott.emp;
    */
    Declare
      Cursor MyCursor  Select   JOB  From  empa  For  Update;
      vSal   emp.Sal%TYPE;
    Begin
      Loop
       Fetch  MyCursor  InTo  vSal;
       Exit  When  MyCursor%NotFound;
       If   vSal < 800 Then
        Delete  From empa  Where  Cursor  Of   MyCursor;
       End  If;  
      End    Loop;
    End;/
Copy after login

What is a display cursor with parameters?

1. Similar to procedures and functions, parameters can be passed to the cursor and used in queries.

The parameters only define the data type, not the size (all formal parameters in Oracle only define the data type, not the size).

与过程不同的是,游标只能接受传递的值,而不能返回值。

  可以给参数设定一个缺省值,当没有参数值传递给游标时,就使用缺省值。

游标中定义的参数只是一个占位符,在别处引用该参数不一定可靠。

2、使用带参数的显示游标

  • 声明带参数的显示游标:

   CURSOR 游标名  [(parameter[,parameter],...)]    IS   Select语句;
Copy after login

参数形式:

1,参数名 数据类型

2,参数名 数据类型 DEFAULT 默认值

例子:

    /*conn scott/tiger
    Crate table  empa  Select * from scott.emp;
    */
    Declare
      Cursor MyCursor(pSal  Number  Default   800)  Select   JOB  From  empa Where  SAL >  pSal ;
      varA  MyCursor%ROWTYPE;
    Begin
      Loop
       Fetch  MyCursor  InTo  varA;
       Exit  When  MyCursor%NotFound;
       DBMS_OUTPUT.PUT_LINE(MyCursor%RowCount||&#39;    &#39;||varA.empno||&#39;    &#39;||varA.ename||&#39;  &#39;||varA.sal); 
      End    Loop;
    End;/
Copy after login

推荐教程:《Oracle教程

The above is the detailed content of what is oracle cursor. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to check tablespace size of oracle How to check tablespace size of oracle Apr 11, 2025 pm 08:15 PM

To query the Oracle tablespace size, follow the following steps: Determine the tablespace name by running the query: SELECT tablespace_name FROM dba_tablespaces; Query the tablespace size by running the query: SELECT sum(bytes) AS total_size, sum(bytes_free) AS available_space, sum(bytes) - sum(bytes_free) AS used_space FROM dba_data_files WHERE tablespace_

How to view instance name of oracle How to view instance name of oracle Apr 11, 2025 pm 08:18 PM

There are three ways to view instance names in Oracle: use the "sqlplus" and "select instance_name from v$instance;" commands on the command line. Use the "show instance_name;" command in SQL*Plus. Check environment variables (ORACLE_SID on Linux) through the operating system's Task Manager, Oracle Enterprise Manager, or through the operating system.

How to encrypt oracle view How to encrypt oracle view Apr 11, 2025 pm 08:30 PM

Oracle View Encryption allows you to encrypt data in the view, thereby enhancing the security of sensitive information. The steps include: 1) creating the master encryption key (MEk); 2) creating an encrypted view, specifying the view and MEk to be encrypted; 3) authorizing users to access the encrypted view. How encrypted views work: When a user querys for an encrypted view, Oracle uses MEk to decrypt data, ensuring that only authorized users can access readable data.

How to uninstall Oracle installation failed How to uninstall Oracle installation failed Apr 11, 2025 pm 08:24 PM

Uninstall method for Oracle installation failure: Close Oracle service, delete Oracle program files and registry keys, uninstall Oracle environment variables, and restart the computer. If the uninstall fails, you can uninstall manually using the Oracle Universal Uninstall Tool.

How to solve the problem of closing oracle cursor How to solve the problem of closing oracle cursor Apr 11, 2025 pm 10:18 PM

The method to solve the Oracle cursor closure problem includes: explicitly closing the cursor using the CLOSE statement. Declare the cursor in the FOR UPDATE clause so that it automatically closes after the scope is ended. Declare the cursor in the USING clause so that it automatically closes when the associated PL/SQL variable is closed. Use exception handling to ensure that the cursor is closed in any exception situation. Use the connection pool to automatically close the cursor. Disable automatic submission and delay cursor closing.

How to check invalid numbers of oracle How to check invalid numbers of oracle Apr 11, 2025 pm 08:27 PM

Oracle Invalid numeric errors may be caused by data type mismatch, numeric overflow, data conversion errors, or data corruption. Troubleshooting steps include checking data types, detecting digital overflows, checking data conversions, checking data corruption, and exploring other possible solutions such as configuring the NLS_NUMERIC_CHARACTERS parameter and enabling data verification logging.

How to create cursors in oracle loop How to create cursors in oracle loop Apr 12, 2025 am 06:18 AM

In Oracle, the FOR LOOP loop can create cursors dynamically. The steps are: 1. Define the cursor type; 2. Create the loop; 3. Create the cursor dynamically; 4. Execute the cursor; 5. Close the cursor. Example: A cursor can be created cycle-by-circuit to display the names and salaries of the top 10 employees.

How to set up users of oracle How to set up users of oracle Apr 11, 2025 pm 08:21 PM

To create a user in Oracle, follow these steps: Create a new user using the CREATE USER statement. Grant the necessary permissions using the GRANT statement. Optional: Use the RESOURCE statement to set the quota. Configure other options such as default roles and temporary tablespaces.

See all articles