mysql存储过程 游标 循环使用介绍
今天分享下自己对于Mysql存储过程的认识与了解,这里主要说说大家常用的游标加循环的嵌套使用
Mysql的存储过程是从版本5才开始支持的,所以目前一般使用的都可以用到存储过程。今天分享下自己对于Mysql存储过程的认识与了解。一些简单的调用以及语法规则这里就不在赘述,网上有许多例子。这里主要说说大家常用的游标加循环的嵌套使用。
首先先介绍循环的分类:
(1)WHILE ... END WHILE
(2)LOOP ... END LOOP
(3)REPEAT ... END REPEAT
(4)GOTO
这里有三种标准的循环方式:WHILE循环,LOOP循环以及REPEAT循环。还有一种非标准的循环方式:GOTO(不做介绍)。
(1)WHILE ... END WHILE
代码如下:
CREATE PROCEDURE p14()
BEGIN
DECLARE v INT;
SET v = 0;
WHILE v INSERT INTO t VALUES (v);
SET v = v + 1;
END WHILE;
END;
这是WHILE循环的方式。它跟IF语句相似,使用"SET v = 0;"语句使为了防止一个常见的错误,如果没有初始化,默认变量值为NULL,而NULL和任何值操作结果都为NULL。
(2)REPEAT ... END REPEAT
代码如下:
CREATE PROCEDURE p15 ()
BEGIN
DECLARE v INT;
SET v = 0;
REPEAT
INSERT INTO t VALUES (v);
SET v = v + 1;
UNTIL v >= 5
END REPEAT;
END;
这是REPEAT循环的例子,功能和前面WHILE循环一样。区别在于它在执行后检查结果,而WHILE则是执行前检查。类似于do while语句。注意到UNTIL语句后面没有分号,在这里可以不写分号,当然你加上额外的分号更好。
(3)LOOP ... END LOOP
代码如下:
CREATE PROCEDURE p16 ()
BEGIN
DECLARE v INT;
SET v = 0;
loop_label: LOOP
INSERT INTO t VALUES (v);
SET v = v + 1;
IF v >= 5 THEN
LEAVE loop_label;
END IF;
END LOOP;
END;
以上是LOOP循环的例子。LOOP循环不需要初始条件,这点和WHILE循环相似,同时它又和REPEAT循环一样也不需要结束条件。
ITERATE 迭代
如果目标是ITERATE(迭代)语句的话,就必须用到LEAVE语句
代码如下:
CREATE PROCEDURE p20 ()
BEGIN
DECLARE v INT;
SET v = 0;
loop_label: LOOP
IF v = 3 THEN
SET v = v + 1;
ITERATE loop_label;
END IF;
INSERT INTO t VALUES (v);
SET v = v + 1;
IF v >= 5 THEN
LEAVE loop_label;
END IF;
END LOOP;
END;
ITERATE(迭代)语句和LEAVE语句一样也是在循环内部的循环引用, 它有点像C语言中 的“Continue”,同样它可以出现在复合语句中,引用复合语句标号,ITERATE(迭代)意思 是重新开始复合语句。
以上是对于循环的几种情况的介绍。接着就是介绍一个带游标的例子来详细解释。
代码如下:
begin
declare p_feeCode varchar(20);
declare p_feeName varchar(20);
declare p_billMoney float(12);
declare p_schemeMoney float(12);
declare allMoney float(10);
declare allUsedMoney float(10);
declare p_year varchar(50);
declare p_totalCompeleteRate float(12);
declare done int(10);
declare flag int(2);
declare feeCodeCursor cursor for select feeCode from fee;//申明一个游标变量
declare continue handler for not found set done=1;//申明循环结束的标志位
set done=0;
select date_format(now(),'%Y') into p_year;
open feeCodeCursor;//打开游标
loop_label:LOOP
fetch feeCodeCursor into p_feeCode;//将游标插入申明的变量
if done = 1 then
leave loop_label;
else
set flag = 0;
end if;
set p_schemeMoney=0;
set p_billMoney = 0;
select feeName into p_feeName from fee where feeCode=p_feeCode;
select sum(billMoney) into p_billMoney from bill_data where feeCode=p_feeCode and billDate like Concat(p_year, '%');
select schemeMoney into p_schemeMoney from total_scheme where feeCode=p_feeCode and schemeDate like Concat(p_year, '%') limit 1;
if flag = 0 then
set done = 0;
end if;
if p_schemeMoney=0 then
set p_totalCompeleteRate=-1.0;
else
set p_totalCompeleteRate=(1.0*p_billMoney)/p_schemeMoney;
end if;
insert into total_summary values(p_feeCode,p_feeName,p_year,p_billMoney,p_totalCompeleteRate);
commit;
end LOOP;
close feeCodeCursor;//循环结束后需要关闭游标
end
以上只是一个简单的例子来说明如何使用,大家不需要关注具体业务逻辑,只需要关注的是其中标志位值的修改情况,已经循环何时离开。以及游标如何声明,如何使用,至于里面具体的操作和普通的sql语句没有太大区别。此处是用一层循环,至于复杂业务需要需要两层三层,可以继续用同样的方法继续嵌套。以下给出双层嵌套循环的,同样大家只需要关注嵌套结构即可。
代码如下:
begin
declare p_projectID varchar(20);
declare p_projectName varchar(20);
declare p_feeCode varchar(20);
declare p_feeName varchar(20);
declare p_projectSchemeMoney float(10);
declare p_projectMoney float(10);
declare p_billMoney float(10);
declare p_year varchar(50);
declare p_projectFeeCompeleteRate float(10);
declare done1 int(10);
declare done2 int(10);
declare flag int(2);
declare feeCodeCursor cursor for select feeCode from fee;
declare continue handler for not found set done1=1;
set done1=0;
select date_format(now(),'%Y') into p_year;
delete from project_fee_summary;
open feeCodeCursor;
repeat //第一层嵌套开始
fetch feeCodeCursor into p_feeCode;
select feeName into p_feeName from fee where feeCode=p_feeCode;
if not done1 then
begin
declare projectIDCursor cursor for select projectID from project;
declare continue handler for not found set done2 = 1;
set done2=0;
open projectIDCursor;
loop_label:LOOP//第二层嵌套开始
fetch projectIDCursor into p_projectID;
select projectName into p_projectName from project where projectID=p_projectID;
if done2 = 1 then
leave loop_label;
else
set flag = 0;
end if;
if not done2 then
set p_projectSchemeMoney=0;
select sum(billMoney) into p_billMoney from bill_data where feeCode=p_feeCode and projectID=p_projectID and billDate like Concat(p_year, '%');
select projectSchemeMoney into p_projectSchemeMoney from project_scheme where feeCode=p_feeCode and projectID=p_projectID;
if flag = 0 then
set done2 = 0;
end if;
if p_projectSchemeMoney=0 then
set p_projectFeeCompeleteRate=-1;
else
set p_projectFeeCompeleteRate=(1.0*p_billMoney)/p_projectSchemeMoney;
end if;
insert into project_fee_summary values(p_feeCode,p_projectID,p_projectName,p_feeName,p_year,p_billMoney,p_projectFeeCompeleteRate,p_projectFeeCompeleteRate);
end if;
end LOOP;
select sum(billMoney) into p_projectMoney from bill_data where feeCode=p_feeCode and billDate like Concat(p_year, '%');
set p_projectFeeCompeleteRate=(1.0*p_projectMoney)/p_projectSchemeMoney;
insert into project_fee_summary values(p_feeCode,"total","total",p_feeName,p_year,p_projectMoney,p_projectFeeCompeleteRate,p_projectFeeCompeleteRate);
close projectIDCursor;
end;
end if;
until done1
end repeat;
close feeCodeCursor;
end

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Windows 11 has a seemingly unlimited amount of customization options, from default settings to every third-party app on the Internet. There are even apps that can change the appearance of your mouse cursor. Modifying the cursor is a great way to give your computer a unique look. You don't have to stick the same boring black and white pointer on every computer. But even so, you don't have to download software to change the look of your cursor. How to change the appearance of the cursor? Windows 11 offers a small amount of customization for the cursor. You can change the cursor by going into Control Panel and selecting Mouse Options there. A new window called "Mouse Properties" will appear. In the mouse properties you can change the color scheme, size and design. Your computer will naturally

Lambda expression breaks out of the loop, specific code examples are needed. In programming, the loop structure is an important syntax that is often used. However, in certain circumstances, we may want to break out of the entire loop when a certain condition is met within the loop body, rather than just terminating the current loop iteration. At this time, the characteristics of lambda expressions can help us achieve the goal of jumping out of the loop. Lambda expression is a way to declare an anonymous function, which can define simple function logic internally. It is different from an ordinary function declaration,

Note: This article compares loops and recursion from the perspective of Go language. When writing programs, you often encounter situations where a series of data or operations need to be processed repeatedly. To achieve this we need to use loops or recursion. Loops and recursions are both commonly used processing methods, but in practical applications, they each have advantages and disadvantages, so the actual situation needs to be considered when choosing which method to use. This article will conduct a comparative study of loops and recursion in the Go language. 1. Loops A loop is a mechanism that repeatedly executes a certain piece of code. There are three main types of Go language

Replacement of recursive calls in Java functions with iteration In Java, recursion is a powerful tool used to solve various problems. However, in some cases, using iteration may be a better option because it is more efficient and less prone to stack overflows. Here are the advantages of iteration: More efficient since it does not require the creation of a new stack frame for each recursive call. Stack overflows are less likely to occur because stack space usage is limited. Iterative methods as an alternative to recursive calls: There are several methods in Java to convert recursive functions into iterative functions. 1. Use the stack Using the stack is the easiest way to convert a recursive function into an iterative function. The stack is a last-in-first-out (LIFO) data structure, similar to a function call stack. publicintfa

This article will explain in detail how PHP returns all the values of an array to form an array. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. Using the array_values() function The array_values() function returns an array of all the values in an array. It does not preserve the keys of the original array. $array=["foo"=>"bar","baz"=>"qux"];$values=array_values($array);//$values will be ["bar","qux"]Using a loop can Use a loop to manually get all the values of the array and add them to a new

Iterator interface The Iterator interface is an interface used to traverse collections. It provides several methods, including hasNext(), next() and remove(). The hasNext() method returns a Boolean value indicating whether there is a next element in the collection. The next() method returns the next element in the collection and removes it from the collection. The remove() method removes the current element from the collection. The following code example demonstrates how to use the Iterator interface to iterate over a collection: Listnames=Arrays.asList("John","Mary","Bob");Iterator

All programming languages are inseparable from loops. So, by default, we start executing a loop whenever there is a repeating operation. But when we are dealing with large number of iterations (millions/billions of rows), using loops is a crime. You might be stuck for a few hours, only to realize later that it doesn't work. This is where implementing vectorization in python becomes very critical. What is vectorization? Vectorization is a technique for implementing (NumPy) array operations on data sets. Behind the scenes, it applies the operation to all elements of the array or series at once (unlike a "for" loop that operates one row at a time). Next we use some use cases to demonstrate what vectorization is. Find the sum of numbers##Use the loop importtimestart

Getting Started with Python Code: 5 Essential Examples for Learning Python is a simple and easy-to-learn high-level programming language that is widely used in data analysis, machine learning, web crawlers and other fields. For beginners, it is important to master some basic Python code. This article will introduce 5 simple example codes to help beginners quickly get started with Python programming. Print Hello,World!print("Hello,World!") This is Python
