search
HomeDatabaseMysql TutorialOracle游标—for、loop、if结合应用

什么时候会用到Oracle游标,以及其中的for、loop、if呢?

一、需求

什么时候会用到Oracle游标,以及其中的for、loop、if呢?

先看这样一个需求:

有一张学生授课表T_TEACHING,每个学生都有数门课程:

但是因为某些原因,导致有的学生课程不全(本应该每个学生都有3门课),应该如何把不全的学生检索出来,再给这些学生添加课程呢,并且要求能够快速解决这个问题。

二、分析

我们对需求进行一步步梳理:

1、我们不知道哪个学生课程不全,所以需要循环判断每个学生

通常用for循环:for USER_ID in USER_IDS

2、循环判断每个学生就要拿到所有的学号

select:select USER_ID from  T_TEACHING GROUP BY USER_ID;

3、有了学号,判断这个学生是否缺少课程,然后添加这门课

(1)select:select count(*) from T_TEACHING where USER_ID=@USER_ID and COURSE_ID=@COURSE_ID;

(2)if else 判断

(3)insert:insert into T_TEACHING(COURSE_ID,USER_ID) values (@COURSE_ID,@USER_ID)

通过分析大致的流程出来了,然后再看细节:

我们通过select ..GROUP BY获取了授课表中所有的学号,然后就对这些学号进行循环获取,,关键在于select ..GROUP BY出来如何循环获取。

三、方法

在oracle中提供了“游标”

游标是什么,游标用来处理从数据库中检索的多行记录(使用SELECT语句)。利用游标,程序可以逐个地处理和遍历一次检索返回的整个记录集。

这正是我们想要的!!

结合for循环,我们可以使用for循环游标,格式如下:

 --(1)定义游标
    --关键字cursor
    cursor x is select语句

 --(2)定义游标变量
  y x%rowtype

 --(3)使用for循环来使用这个游标
    for y in x loop

      --逻辑处理

    end loop;

下面我们通过sql存储过程来完整的实现上面的需求

declare
      --定义类型
      cursor t_tea
      is
      select USER_ID from T_TEACHING GROUP BY USER_ID;
      --定义一个游标变量
      t_row t_tea%rowtype;
      --定义一个number类型的临时变量
    v_count number;
 begin
      for t_row in t_tea loop
    select count(*) into v_count from T_TEACHING where USER_ID=t_row.USER_ID and COURSE_ID=02;
     if v_count = 0 then
        insert into T_TEACHING(COURSE_ID,USER_ID) values (02,t_row.USER_ID);
     end if;
      end loop;
end;

四、总结  

Oracle中的游标循环不只有for循环,Oracle中提供了两种游标,显示游标和隐式游标,其他游标的使用方式可以在这里了解,用到了在深入研究:

 

 

 

Statement
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
What are some tools you can use to monitor MySQL performance?What are some tools you can use to monitor MySQL performance?Apr 23, 2025 am 12:21 AM

How to effectively monitor MySQL performance? Use tools such as mysqladmin, SHOWGLOBALSTATUS, PerconaMonitoring and Management (PMM), and MySQL EnterpriseMonitor. 1. Use mysqladmin to view the number of connections. 2. Use SHOWGLOBALSTATUS to view the query number. 3.PMM provides detailed performance data and graphical interface. 4.MySQLEnterpriseMonitor provides rich monitoring functions and alarm mechanisms.

How does MySQL differ from SQL Server?How does MySQL differ from SQL Server?Apr 23, 2025 am 12:20 AM

The difference between MySQL and SQLServer is: 1) MySQL is open source and suitable for web and embedded systems, 2) SQLServer is a commercial product of Microsoft and is suitable for enterprise-level applications. There are significant differences between the two in storage engine, performance optimization and application scenarios. When choosing, you need to consider project size and future scalability.

In what scenarios might you choose SQL Server over MySQL?In what scenarios might you choose SQL Server over MySQL?Apr 23, 2025 am 12:20 AM

In enterprise-level application scenarios that require high availability, advanced security and good integration, SQLServer should be chosen instead of MySQL. 1) SQLServer provides enterprise-level features such as high availability and advanced security. 2) It is closely integrated with Microsoft ecosystems such as VisualStudio and PowerBI. 3) SQLServer performs excellent in performance optimization and supports memory-optimized tables and column storage indexes.

How does MySQL handle character sets and collations?How does MySQL handle character sets and collations?Apr 23, 2025 am 12:19 AM

MySQLmanagescharactersetsandcollationsbyusingUTF-8asthedefault,allowingconfigurationatdatabase,table,andcolumnlevels,andrequiringcarefulalignmenttoavoidmismatches.1)Setdefaultcharactersetandcollationforadatabase.2)Configurecharactersetandcollationfor

What are triggers in MySQL?What are triggers in MySQL?Apr 23, 2025 am 12:11 AM

A MySQL trigger is an automatically executed stored procedure associated with a table that is used to perform a series of operations when a specific data operation is performed. 1) Trigger definition and function: used for data verification, logging, etc. 2) Working principle: It is divided into BEFORE and AFTER, and supports row-level triggering. 3) Example of use: Can be used to record salary changes or update inventory. 4) Debugging skills: Use SHOWTRIGGERS and SHOWCREATETRIGGER commands. 5) Performance optimization: Avoid complex operations, use indexes, and manage transactions.

How do you create and manage user accounts in MySQL?How do you create and manage user accounts in MySQL?Apr 22, 2025 pm 06:05 PM

The steps to create and manage user accounts in MySQL are as follows: 1. Create a user: Use CREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password'; 2. Assign permissions: Use GRANTSELECT, INSERT, UPDATEONmydatabase.TO'newuser'@'localhost'; 3. Fix permission error: Use REVOKEALLPRIVILEGESONmydatabase.FROM'newuser'@'localhost'; then reassign permissions; 4. Optimization permissions: Use SHOWGRA

How does MySQL differ from Oracle?How does MySQL differ from Oracle?Apr 22, 2025 pm 05:57 PM

MySQL is suitable for rapid development and small and medium-sized applications, while Oracle is suitable for large enterprises and high availability needs. 1) MySQL is open source and easy to use, suitable for web applications and small and medium-sized enterprises. 2) Oracle is powerful and suitable for large enterprises and government agencies. 3) MySQL supports a variety of storage engines, and Oracle provides rich enterprise-level functions.

What are the disadvantages of using MySQL compared to other relational databases?What are the disadvantages of using MySQL compared to other relational databases?Apr 22, 2025 pm 05:49 PM

The disadvantages of MySQL compared to other relational databases include: 1. Performance issues: You may encounter bottlenecks when processing large-scale data, and PostgreSQL performs better in complex queries and big data processing. 2. Scalability: The horizontal scaling ability is not as good as Google Spanner and Amazon Aurora. 3. Functional limitations: Not as good as PostgreSQL and Oracle in advanced functions, some functions require more custom code and maintenance.

See all articles

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools