Home Database Mysql Tutorial MySQL 5.0 新特性教程 存储过程:第二讲_MySQL

MySQL 5.0 新特性教程 存储过程:第二讲_MySQL

Jun 01, 2016 pm 02:04 PM
sql storage Tutorial characteristic process

作者:mysql AB;翻译:陈朋奕

  Why MySQL Statements are Legal in a Procedure Body
  什么MySQL语句在存储过程体中是合法的?

  什么样的SQL语句在Mysql存储过程中才是合法的呢?你可以创建一个包含INSERT, UPDATE,DELETE, SELECT, DROP, CREATE, REPLACE等的语句。你唯一需要记住的是如果代码中包含MySQL扩充功能,那么代码将不能移植。在标准SQL语句中:任何数据库定义语言都是合法的,如:

CREATE PROCEDURE p () DELETE FROM t; //
  SET、COMMIT以及ROLLBACK也是合法的,如:
CREATE PROCEDURE p () SET @x = 5; //

  MySQL的附加功能:任何数据操作语言的语句都将合法。
CREATE PROCEDURE p () DROP TABLE t; //

  MySQL扩充功能:直接的SELECT也是合法的:
CREATE PROCEDURE p () SELECT 'a'; //

  顺便提一下,我将存储过程中包括DDL语句的功能称为MySQL附加功能的原因是在SQL标准中把这个定义为非核心的,即可选组件。

  在过程体中有一个约束,就是不能有对例程或表操作的数据库操作语句。例如下面的例子就是非法的:
CREATE PROCEDURE p1 ()
CREATE PROCEDURE p2 () DELETE FROM t; //

  下面这些对MySQL 5.0来说全新的语句,过程体中是非法的:
CREATE PROCEDURE, ALTER PROCEDURE, DROP PROCEDURE, CREATE FUNCTION,
DROP FUNCTION, CREATE TRIGGER, DROP TRIGGER.

  不过你可以使用
CREATE PROCEDURE db5.p1 () DROP DATABASE db5//

  但是类似
"USE database"

  语句也是非法的,因为MySQL假定默认数据库就是过程的工作场所。

  Call the Procedure 调用存储过程
  1.
  现在我们就可以调用一个存储过程了,你所需要输入的全部就是CALL和你过程名以及一个括号再一次强调,括号是必须的当你调用例子里面的p1过程时,结果是屏幕返回了t表的内容
mysql> CALL p1() //
------
| s1 |
------
| 5 |
------
1 row in set (0.03 sec)
Query OK, 0 rows affected (0.03 sec)

  因为过程中的语句是
"SELECT * FROM t;"

  2. Let me say that again, another way.
  其他实现方式
mysql> CALL p1() //

  和下面语句的执行效果一样:
mysql> SELECT * FROM t; //

  所以,你调用p1过程就相当于你执行了下面语句:
"SELECT * FROM t;"

  好了,主要的知识点"创建和调用过程方法"已经清楚了。我希望你能对自己说这相当简单。但是很快我们就有一系列的练习,每次都加一条子句,或者改变已经存在的子句。那样在写复杂部件前我们将会有很多可用的子句。

Characteristics Clauses 特征子句
  1.
CREATE PROCEDURE p2 ()
LANGUAGE SQL NOT DETERMINISTIC SQL SECURITY DEFINER COMMENT 'A Procedure' SELECT CURRENT_DATE, RAND() FROM t //

  这里我给出的是一些能反映存储过程特性的子句。子句内容在括号之后,主体之前。这些子句都是可选的,他们有什么作用呢?

  2.
CREATE PROCEDURE p2 ()
LANGUAGE SQL NOT DETERMINISTIC
SQL SECURITY DEFINER
COMMENT 'A Procedure'
SELECT CURRENT_DATE, RAND() FROM t //

  很好,这个LANGUAGE SQL子句是没有作用的。仅是为了说明下面过程的主体使用SQL语言编写。这条是系统默认的,但你在这里声明是有用的,因为某些DBMS(IBM的DB2)需要它,如果你关注DB2的兼容问题最好还是用上。此外,今后可能会出现除SQL外的其他语言支持的存储过程。

  3.
CREATE PROCEDURE p2 ()
LANGUAGE SQL
NOT DETERMINISTIC SQL SECURITY DEFINER
COMMENT 'A Procedure'
SELECT CURRENT_DATE, RAND() FROM t //

  下一个子句,NOT DETERMINISTIC,是传递给系统的信息。这里一个确定过程的定义就是那些每次输入一样输出也一样的程序。在这个案例中,既然主体中含有SELECT语句,那返回肯定是未知的因此我们称其NOT DETERMINISTIC。但是MySQL内置的优化程序不会注意这个,至少在现在不注意。

  4.
CREATE PROCEDURE p2 ()
LANGUAGE SQL
NOT DETERMINISTIC
SQL SECURITY DEFINER COMMENT 'A Procedure'
SELECT CURRENT_DATE, RAND() FROM t //
  下一个子句是SQL SECURITY,可以定义为SQL SECURITY DEFINER或SQL SECURITY INVOKER。
  这就进入了权限控制的领域了,当然我们在后面将会有测试权限的例子。
SQL SECURITY DEFINER

  意味着在调用时检查创建过程用户的权限(另一个选项是SQLSECURITY INVOKER)。
  现在而言,使用
SQL SECURITY DEFINER

  指令告诉MySQL服务器检查创建过程的用户就可以了,当过程已经被调用,就不检查执行调用过程的用户了。而另一个选项(INVOKER)则是告诉服务器在这一步仍然要检查调用者的权限。

  5.
CREATE PROCEDURE p2 ()
LANGUAGE SQL
NOT DETERMINISTIC
SQL SECURITY DEFINER
COMMENT 'A Procedure' SELECT CURRENT_DATE, RAND() FROM t //

  COMMENT 'A procedure'
  是一个可选的注释说明。

  最后,注释子句会跟过程定义存储在一起。这个没有固定的标准,我在文中会指出没有固定标准的语句,不过幸运的是这些在我们标准的SQL中很少。

  6.
CREATE PROCEDURE p2 ()
LANGUAGE SQL
NOT DETERMINISTIC
SQL SECURITY DEFINER
COMMENT ''
SELECT CURRENT_DATE, RAND() FROM t //

  上面过程跟下面语句是等效的:
CREATE PROCEDURE p2 ()
SELECT CURRENT_DATE, RAND() FROM t //

  特征子句也有默认值,如果省略了就相当于:
LANGUAGE SQL NOT DETERMINISTIC SQL SECURITY DEFINER COMMENT ''

Digressions一些题外话

  Digression:
  调用p2()//的结果
mysql> call p2() //
-------------- -----------------
| CURRENT_DATE | RAND() |
-------------- -----------------
| 2004-11-09 | 0.7822275075896 |
-------------- -----------------
1 row in set (0.26 sec)
Query OK, 0 rows affected (0.26 sec)
  当调用过程p2时,一个SELECT语句被执行返回我们期望获得的随机数。
  Digression: sql_mode unchanging
  不会改变的

sql_mode
mysql> set sql_mode='ansi' //
mysql> create procedure p3()select'a'||'b'//
mysql> set sql_mode=''//
mysql> call p3()//
------------
| 'a' || 'b' |
------------
| ab |
------------

  MySQL在过程创建时会自动保持运行环境。例如:我们需要使用两条竖线来连接字符串但是这只有在sql mode为ansi的时候才合法。如果我们将sql mode改为non-ansi,不用担心,它仍然能工作,只要它第一次使用时能正常工作。

Exercise 练习

  Question
  问题
  如果你不介意练习一下的话,试能否不看后面的答案就能处理这些请求。
  创建一个过程,显示`Hello world`。用大约5秒时间去思考这个问题,既然你已经学到了这里,这个应该很简单。当你思考问题的时候,我们再随机选择一些刚才讲过的东西复习:
  DETERMINISTIC
  (确定性)子句是反映输出和输入依赖特性的子句…调用过程使用CALL过程名(参数列表)方式。好了,我猜时间也到了。

  Answer
  答案
  好的,答案就是在过程体中包含
"SELECT 'Hello, world'"
  语句
  MySQL
mysql> CREATE PROCEDURE p4 () SELECT 'Hello, world' //
Query OK, 0 rows affected (0.00 sec)
mysql> CALL p4()//
--------------
| Hello, world |
--------------
| Hello, world |
--------------
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)

Parameters 参数

  让我们更进一步的研究怎么在存储过程中定义参数
  1. CREATE PROCEDURE p5
  () ...
  2. CREATE PROCEDURE p5
  ([IN] name data-type) ...
  3. CREATE PROCEDURE p5
  (OUT name data-type) ...
  4. CREATE PROCEDURE p5
  (INOUT name data-type) ...

  回忆一下前面讲过的参数列表必须在存储过程名后的括号中。上面的第一个例子中的参数列表是空的,第二个例子中有一个输入参数。这里的词IN可选,因为默认参数为IN(input)。

  第三个例子中有一个输出参数,第四个例子中有一个参数,既能作为输入也可以作为输出。
  IN example 输入的例子
mysql> CREATE PROCEDURE p5(p INT) SET @x = p //
Query OK, 0 rows affected (0.00 sec)
mysql> CALL p5(12345)//
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @x//
-------
| @x |
-------
| 12345 |
-------
1 row in set (0.00 sec)

  这个IN的例子演示的是有输入参数的过程。在过程体中我将会话变量x设定为参数p的值。然后调用过程,将12345传入参数p。选择显示会话变量@x,证明我们已经将参数值12345传入。
  OUT example 输出的例子
mysql> CREATE PROCEDURE p6 (OUT p INT)
-> SET p = -5 //
mysql> CALL p6(@y)//
mysql> SELECT @y//
------
| @y |
------
| -5 |
------

  这是另一个例子。这次的p是输出参数,然后在过程调用中将p的值传入会话变量@y中。

  在过程体中,我们给参数赋值-5,在调用后我们可以看出,OUT是告诉DBMS值是从过程中传出的。
  同样我们可以用语句
"SET @y = -5;"

  来达到同样的效果

Compound Statements 复合语句

  现在我们展开的详细分析一下过程体:
CREATE PROCEDURE p7 ()
BEGIN
SET @a = 5;
SET @b = 5;
INSERT INTO t VALUES (@a);
SELECT s1 * @a FROM t WHERE s1 >= @b;
END; // /* I won't CALL this.
这个语句将不会被调用
*/

  完成过程体的构造就是BEGIN/END块。这个BEGIN/END语句块和Pascal语言中的BEGIN/END是基本相同的,和C语言的框架是很相似的。我们可以使用块去封装多条语句。在这个例子中,我们使用了多条设定会话变量的语句,然后完成了一些insert和select语句。如果你的过程体中有多条语句,那么你就需要BEGIN/END块了。BEGIN/END块也被称为复合语句,在这里你可以进行变量定义和流程控制。

  未完待续...

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)

What is the difference between HQL and SQL in Hibernate framework? What is the difference between HQL and SQL in Hibernate framework? Apr 17, 2024 pm 02:57 PM

HQL and SQL are compared in the Hibernate framework: HQL (1. Object-oriented syntax, 2. Database-independent queries, 3. Type safety), while SQL directly operates the database (1. Database-independent standards, 2. Complex executable queries and data manipulation).

In summer, you must try shooting a rainbow In summer, you must try shooting a rainbow Jul 21, 2024 pm 05:16 PM

After rain in summer, you can often see a beautiful and magical special weather scene - rainbow. This is also a rare scene that can be encountered in photography, and it is very photogenic. There are several conditions for a rainbow to appear: first, there are enough water droplets in the air, and second, the sun shines at a low angle. Therefore, it is easiest to see a rainbow in the afternoon after the rain has cleared up. However, the formation of a rainbow is greatly affected by weather, light and other conditions, so it generally only lasts for a short period of time, and the best viewing and shooting time is even shorter. So when you encounter a rainbow, how can you properly record it and photograph it with quality? 1. Look for rainbows. In addition to the conditions mentioned above, rainbows usually appear in the direction of sunlight, that is, if the sun shines from west to east, rainbows are more likely to appear in the east.

Tutorial on how to turn off the payment sound on WeChat Tutorial on how to turn off the payment sound on WeChat Mar 26, 2024 am 08:30 AM

1. First open WeChat. 2. Click [+] in the upper right corner. 3. Click the QR code to collect payment. 4. Click the three small dots in the upper right corner. 5. Click to close the voice reminder for payment arrival.

PHP Tutorial: How to convert int type to string PHP Tutorial: How to convert int type to string Mar 27, 2024 pm 06:03 PM

PHP Tutorial: How to Convert Int Type to String In PHP, converting integer data to string is a common operation. This tutorial will introduce how to use PHP's built-in functions to convert the int type to a string, while providing specific code examples. Use cast: In PHP, you can use cast to convert integer data into a string. This method is very simple. You only need to add (string) before the integer data to convert it into a string. Below is a simple sample code

A simple tutorial on converting full-width English letters to half-width letters A simple tutorial on converting full-width English letters to half-width letters Mar 25, 2024 pm 09:21 PM

When using a computer to input English, sometimes we encounter the difference between full-width English letters and half-width English letters. Full-width English letters refer to the characters input by pressing the Shift key and the English letter key combination when the input method is Chinese mode. They occupy a full-width character width. Half-width English letters refer to characters input directly when the input method is English mode, and they occupy half a character width. In some cases, we may need to convert full-width English letters to half-width letters. Here is a simple tutorial: First, open a text editor or any

How to retrieve the wrong chain of virtual currency? Tutorial on retrieving the wrong chain of virtual currency transfer How to retrieve the wrong chain of virtual currency? Tutorial on retrieving the wrong chain of virtual currency transfer Jul 16, 2024 pm 09:02 PM

The expansion of the virtual market is inseparable from the circulation of virtual currency, and naturally it is also inseparable from the issue of virtual currency transfers. A common transfer error is the address copy error, and another error is the chain selection error. The transfer of virtual currency to the wrong chain is still a thorny problem, but due to the inexperience of transfer operations, novices often transfer the wrong chain. So how to recover the wrong chain of virtual currency? The wrong link can be retrieved through a third-party platform, but it may not be successful. Next, the editor will tell you in detail to help you better take care of your virtual assets. How to retrieve the wrong chain of virtual currency? The process of retrieving virtual currency transferred to the wrong chain may be complicated and challenging, but by confirming the transfer details, contacting the exchange or wallet provider, importing the private key to a compatible wallet, and using the cross-chain bridge tool

Why do you need to know histograms to learn photography? Why do you need to know histograms to learn photography? Jul 20, 2024 pm 09:20 PM

In daily shooting, many people encounter this situation: the photos on the camera seem to be exposed normally, but after exporting the photos, they find that their true form is far from the camera's rendering, and there is obviously an exposure problem. Affected by environmental light, screen brightness and other factors, this situation is relatively normal, but it also brings us a revelation: when looking at photos and analyzing photos, you must learn to read histograms. So, what is a histogram? Simply understood, a histogram is a display form of the brightness distribution of photo pixels: horizontally, the histogram can be roughly divided into three parts, the left side is the shadow area, the middle is the midtone area, and the right side is the highlight area; On the left is the dead black area in the shadows, while on the far right is the spilled area in the highlights. The vertical axis represents the specific distribution of pixels

C++ function types and characteristics C++ function types and characteristics Apr 11, 2024 pm 03:30 PM

C++ functions have the following types: simple functions, const functions, static functions, and virtual functions; features include: inline functions, default parameters, reference returns, and overloaded functions. For example, the calculateArea function uses π to calculate the area of ​​a circle of a given radius and returns it as output.

See all articles