1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
# 1、空参列表
# 案例:插入到admin表中5条记录
USE girls;
SELECT * FROM admin;
DELIMITER $$
CREATE PROCEDURE myp1()
BEGIN
INSERT INTO admin(username, `password`)
VALUES('john1', '0000'),('lily', '0000'),('rose', '0000'),('jack', '0000'),('tom', '0000');
END $$
# 调用
CALL myp1()$$
# 2、创建带IN模式参数的存储过程
# 案例1:创建存储过程实现:根据女神名,查询对应的男神信息
CREATE PROCEDURE myp2(IN beautyName VARCHAR(20))
BEGIN
SELECT bo.*
FROM boys bo
RIGHT JOIN beauty b
ON bo.id = b.boyfriend_id
WHERE b.name = beautyName;
END $$
# 调用
CALL myp2('柳岩')$$
# 案例2:创建存储过程实现,用户是否登录成功
CREATE PROCEDURE myp3(IN username VARCHAR(20), IN PASSWORD VARCHAR(20))
BEGIN
DECLARE result INT DEFAULT 0; # 声明并初始化
SELECT COUNT(*) INTO result # 赋值
FROM admin
WHERE admin.username = username
AND admin.password = PASSWORD;
SELECT IF (result > 0, '成功', '失败'); # 使用
END $$
# 调用
CALL myp3('张三', '8888')$$
# 3、创建带OUT模式的存储过程
# 案例1:根据女神名,返回对应的男神名
CREATE PROCEDURE myp4(IN beautyName VARCHAR(20), OUT boyName VARCHAR(20))
BEGIN
SELECT bo.boyName INTO boyName
FROM boys bo
JOIN beauty b
ON bo.id = b.boyfriend_id
WHERE b.name = beautyName;
END $$
# 调用
SET @bName$$
CALL myp4('小昭',@bName)$$
SELECT @bName$$
# 案例2:根据女神名,返回对应的男神名和男神魅力值
CREATE PROCEDURE myp5(IN beautyName VARCHAR(20), OUT boyName VARCHAR(20), OUT userCP INT)
BEGIN
SELECT bo.boyName, bo.userCP INTO boyName, userCP
FROM boys bo
JOIN beauty b
ON bo.id = b.boyfriend_id
WHERE b.name = beautyName;
END
# 调用
CALL myp5('小昭', @nName, @userCP);
SELECT @bName, @userCP;
# 4、创建带INOUT模式参数的存储过程
# 案例1:传入a和b两个值,最终a和b都翻倍并返回
CREATE PROCEDURE myp6(INOUT a INT, INOUT b INT)
BEGIN
SET a = a * 2;
SET b = b * 2;
END
# 调用
SET @m = 10;
SET @n = 20;
CALL myp6 (@m, @n);
SELECT @m, @n;
|