Home Database Mysql Tutorial MySQL存储过程编程教程读书笔记-第二章MySQL存储过程编程指南-存_MySQL

MySQL存储过程编程教程读书笔记-第二章MySQL存储过程编程指南-存_MySQL

Jun 01, 2016 pm 01:26 PM
number Programming Tutorial programming language reading notes

bitsCN.com

MySQL存储过程编程时一个复杂的主题,我们将在本章中为你提供完成基本任务的内容,其中包括:

1、怎样创建存储过程

2、存储过程怎样进行输入输出

3、怎样和数据库交互

4、怎样用MySQL存储编程语言创建过程,函数和触发器

第一个存储过程实例:

delimiter $$drop procedure if exists HelloWorld$$create procedure HelloWorld()begin     select "Hello World";end $$变量 
Copy after login

本地变量可以用declare语句进行声明。变量名称必须遵循MySQL的列明规则,并且可以使MySQL内建的任何数据类型。你可以用default字句给变量一个初始值,并且可以用SET语句给变量赋一个新值

delimiter $$drop procedure if exists variable_demo$$begin     declare my_integer int;    declare my_big_integer bigint;    declare my_currency numeric(8, 2);    declare my_pi float        default 3.1415926;    declare my_text text;    declare my_dob date        default '1960-06-21';    declare my_varchar varchar(30)        default "Hello World!";    set my_integer = 20;    set my_big_integer = power(my_integer, 3);end $$delimiter;
Copy after login

参数

参数可以使我们的存储程序更为灵活,更为实用。参数包括IN(只读模式), INOUT(可读写模式)和OUT(只写模式)。IN模式作为缺省的参数模式。

IN:任何对于该参数的修改都不会返回给调用它的程序

OUT:这个模式意味着存储过程可以对参数赋值(修改参数的值),并且这个被修改的值会被返回给它的调用程序

INOUT:这个模式意味着存储过程即可读取传入的参数,而且任何对于该参数的修改对于它的调用程序而言都是可见的

对于存储函数而言,只能使用IN模式

delimiter $$drop procedure if exists my_sqrt$$create procedure my_sqrt(input_number int, out out_number float)begin    set out_number = SQRT(input_number);end $$delimiter;
Copy after login
创建和执行使用OUT参数的存储过程
call my_sqrt(12, @out_value) $$select @out_value $$条件执行
Copy after login

通过购买量的多少来计算出贴现率的存储程序,购买量超过$500可以返回20%,购买量超过$100可以返回10%。

delimiter $$drop procedure if exists discounted_price$$create procedure discounted_price(normal_price NUMERIC(8, 2), out discount_price NUMBERIC(8, 2))begin     if (normal_price > 500) then         set discount_price = normal_price*.8;    else if (normal_price > 100) then         set discount_price = normal_price*.9;    else         set discount_price = normal_price;    end if;end$$delimiter;循环
Copy after login

MySQL存储程序语言提供了三种类型的循环

使用LOOP和END LOOP字句的简单循环

当循环条件为真时继续执行的循环,使用WHILE和END WHILE字句

循环直至条件为真,使用REPEAT和UNTIL字句

在这三种循环中,你都可以使用LEAVE字句来终止循环

DELIMITER $$DROP PROCEDURE IF EXISTS simple_loop$$CREATE PROCEDURE simple_loop()BEGIN    DECLARE counter INT DEFAULT 0;    my_simple_loop: LOOP        SET counter = counter 1;        IF counter = 10 THEN           LEAVE my_simple_loop;        END IF;    END IF;END LOOP my_simple_loop;select "I can count to 10";END$$ DELIMITER;错误处理
Copy after login

1、如果你认为内嵌的SQL语句会返回空记录,或者你想用游标捕获SELECT语句所返回的记录,那么一个NO FOUND 错误处理可以防止存储过程过早的被终止

2、如果你认为SQL语句可能返回错误(比如违背约束条件),你可以创建一个错误处理来阻止程序终止。这个处理将代替你的默认错误处理并继续程序的执行。

和数据库交互

大多数存储过程包含了各种和数据库表的交互,它们包括四种主要的交互:

1、将一个SQL语句所返回的单个记录放入本地变量中。

2、创建一个“游标”来迭代SQL语句所返回的结果集

3、执行一个SQL语句,将执行后的结果集返回给它的调用程序

4、内嵌一个不反悔结果集的SQL语句,如INSERT,UPDATE, DELETE等

对本地变量使用SELECT INTO

当需要在单个记录数据中获取查询信息,你就可以使用SELECT INTO 语法(无论是使用单个记录,多个记录的混合数据,还是多个表连接)。在这种情况下,你可以再SELECT语句中跟随一个INTO子句,告诉MySQL得到的查询数据返回给谁

DELIMITER $$ DROP PROCEDURE IF EXISTS customer_sales $$ CREATE PROCEDURE customer_sales(int_customer_id INT) READS SQL DATA BEGIN DECLARE total_sales NUMERIC(8, 2); SELECT SUM(sale_value) INTO total_sales FROM sales WHERE customer_id = in_customer_id; SELECT CONCAT('Total sales for ', in_customer_id, 'is', 'total_sales'); END; $$
Copy after login

使用游标

SELECT INTO 定义了单记录查询,但是很多应用程序要求查询多记录数据,你可以使用MySQL中的游标来实现这一切,游标允许你将一个或更多的SQL结果集放进存储程序变量中,通常用来执行结果集中各个单记录的处理。

DELIMITER $$ DROP PROCEDURE cursor_example() READ SQL DATA BEGIN DECLARE l_employee_id INT; DECLARE l_salary NUMERIC(8, 2); DECLARE l_department_id INT; DECLARE done INT DEFAULT 0; DECLARE curl CURSOR FOR SELECT employee_id, salary, department_id FROM employees; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; OPEN curl; emp_loop : LOOP FETCH curl INTO l_employee_id, l_salary, l_department_id; IF done = 1 THEN LEAVE emp_loop; END IF; END LOOP emp_loop;
Copy after login
CLOSE curl;
END;$$ bitsCN.com
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Huawei's official introductory tutorial for Cangjie programming language is released. Learn how to obtain the universal version SDK in one article Huawei's official introductory tutorial for Cangjie programming language is released. Learn how to obtain the universal version SDK in one article Jun 25, 2024 am 08:05 AM

According to news from this site on June 24, at the keynote speech of the HDC2024 Huawei Developer Conference on June 21, Gong Ti, President of Huawei Terminal BG Software Department, officially announced Huawei’s self-developed Cangjie programming language. This language has been developed for 5 years and is now available for developer preview. Huawei's official developer website has now launched the official introductory tutorial video of Cangjie programming language to facilitate developers to get started and understand it. This tutorial will take users to experience Cangjie, learn Cangjie, and apply Cangjie, including using Cangjie language to estimate pi, calculate the stem and branch rules for each month of 2024, see N ways of expressing binary trees in Cangjie language, and use enumeration types to implement Algebraic calculations, signal system simulation using interfaces and extensions, and new syntax using Cangjie macros, etc. This site has tutorial access address: ht

After 5 years of research and development, Huawei's next-generation programming language 'Cangjie” has officially launched its preview After 5 years of research and development, Huawei's next-generation programming language 'Cangjie” has officially launched its preview Jun 22, 2024 am 09:54 AM

This site reported on June 21 that at the HDC2024 Huawei Developer Conference this afternoon, Gong Ti, President of Huawei Terminal BG Software Department, officially announced Huawei’s self-developed Cangjie programming language and released a developer preview version of HarmonyOSNEXT Cangjie language. This is the first time Huawei has publicly released the Cangjie programming language. Gong Ti said: "In 2019, the Cangjie programming language project was born at Huawei. After 5 years of R&D accumulation and heavy R&D investment, it finally meets global developers today. Cangjie programming language integrates modern language features, comprehensive compilation optimization and Runtime implementation and out-of-the-box IDE tool chain support create a friendly development experience and excellent program performance for developers. "According to reports, Cangjie programming language is an all-scenario intelligence tool.

Huawei launches HarmonyOS NEXT Cangjie programming language developer preview beta recruitment Huawei launches HarmonyOS NEXT Cangjie programming language developer preview beta recruitment Jun 22, 2024 am 04:07 AM

According to news from this site on June 21, Huawei’s self-developed Cangjie programming language was officially unveiled today, and the official announced the launch of HarmonyOSNEXT Cangjie language developer preview version Beta recruitment. This upgrade is an early adopter upgrade to the developer preview version, which provides Cangjie language SDK, developer guides and related DevEcoStudio plug-ins for developers to use Cangjie language to develop, debug and run HarmonyOSNext applications. Registration period: June 21, 2024 - October 21, 2024 Application requirements: This HarmonyOSNEXT Cangjie Language Developer Preview Beta recruitment event is only open to the following developers: 1) Real names have been completed in the Huawei Developer Alliance Certification; 2) Complete H

Tianjin University and Beihang University are deeply involved in Huawei's 'Cangjie” project and launched the first AI agent programming framework 'Cangqiong” based on domestic programming languages. Tianjin University and Beihang University are deeply involved in Huawei's 'Cangjie” project and launched the first AI agent programming framework 'Cangqiong” based on domestic programming languages. Jun 23, 2024 am 08:37 AM

According to news from this site on June 22, Huawei yesterday introduced Huawei’s self-developed programming language-Cangjie to developers around the world. This is the first public appearance of Cangjie programming language. According to inquiries on this site, Tianjin University and Beijing University of Aeronautics and Astronautics were deeply involved in the research and development of Huawei’s “Cangjie”. Tianjin University: Cangjie Programming Language Compiler The software engineering team of the Department of Intelligence and Computing of Tianjin University joined hands with the Huawei Cangjie team to deeply participate in the quality assurance research of the Cangjie programming language compiler. According to reports, the Cangjie compiler is the basic software that is symbiotic with the Cangjie programming language. In the preparatory stage of the Cangjie programming language, a high-quality compiler that matches it became one of the core goals. As the Cangjie programming language evolves, the Cangjie compiler is constantly being upgraded and improved. In the past five years, Tianjin University

What should I do if the Microsoft Edge browser does not display images? - What to do if the Microsoft Edge browser does not display images? What should I do if the Microsoft Edge browser does not display images? - What to do if the Microsoft Edge browser does not display images? Mar 04, 2024 pm 07:43 PM

Recently, many friends have asked the editor what to do if the Microsoft Edge browser does not display images. Next, let us learn how to solve the problem of Microsoft Edge browser not displaying images. I hope it can help everyone. 1. First click on the lower left corner to start, and right-click on "Microsoft Edge Browser", as shown in the figure below. 2. Then select "More" and click "App Settings", as shown in the figure below. 3. Then scroll down to find "Pictures", as shown in the picture below. 4. Finally, turn on the switch below the picture, as shown in the picture below. The above is all the content that the editor brings to you on what to do if the Microsoft Edge browser does not display pictures. I hope it can be helpful to you.

Huawei's self-developed Cangjie programming language official website and development documents are online, integrating into the Hongmeng ecosystem for the first time Huawei's self-developed Cangjie programming language official website and development documents are online, integrating into the Hongmeng ecosystem for the first time Jun 22, 2024 am 03:10 AM

According to news from this site on June 21, before the HDC2024 Huawei Developer Conference, Huawei’s self-developed Cangjie programming language was officially unveiled, and the Cangjie official website is now online. The official website introduction shows that Cangjie programming language is a new generation programming language for all-scenario intelligence, focusing on "native intelligence, natural all-scenarios, high performance, and strong security." Integrate into the Hongmeng ecosystem to provide developers with a good programming experience. The official website attached to this site introduces as follows: Native intelligent programming framework embedded with AgentDSL, organic integration of natural language & programming language; multi-Agent collaboration, simplified symbolic expression, free combination of patterns, supporting the development of various intelligent applications. Innately lightweight and scalable runtime for all scenes, modular layered design, no matter how small the memory is, it can be accommodated; all-scenario domain expansion

Comparison of the advantages and disadvantages of C++ technology and other modern programming languages Comparison of the advantages and disadvantages of C++ technology and other modern programming languages Jun 01, 2024 pm 10:15 PM

A comparison of the advantages and disadvantages of C++ with other modern programming languages ​​is: C++ advantages: high performance, low-level control, rich library ecosystem. C++ disadvantages: steep learning curve, manual memory management, limited portability. Python advantages: smooth learning curve, extensive library support, interpreted language. Advantages of Java: platform independent, automatic memory management, wide application. Advantages of JavaScript: essential for front-end development, lightweight, dynamic type.

The last link of Huawei's pure-blood Hongmeng ecosystem! Self-developed Cangjie programming language will make its debut The last link of Huawei's pure-blood Hongmeng ecosystem! Self-developed Cangjie programming language will make its debut Jun 21, 2024 pm 03:23 PM

According to news on June 21, this afternoon, Huawei Developer Conference 2024 will be officially opened. "Pure-blood Hongmeng" Harmony OS NEXT is naturally a top priority. According to the plan previously revealed by Yu Chengdong, the public beta may be officially announced this afternoon, and ordinary consumers can also try out "pure-blood Harmony". According to reports, the first batch of supported mobile phones are the Mate60 series and Pura70 series. It is worth noting that as a "pure-blooded Hongmeng", HarmonyOSNEXT has removed the traditional Linux kernel and AOSP Android open source code and developed the entire stack in-house. According to the latest report from Sina Technology, Huawei will also complete the last link of Hongmeng Ecosystem and expand its presence in the world.

See all articles