札记之MySQL存储过程简单应用

对接网贷机构,涉及到数据的check,面对数百行不同sql语句的时候,该如何处理?小记一下~

PHP处理方法;
使用正则分隔换行和分号 preg_split(“/;[\r\n]+/“, filecontent)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public function checkKip()
{
$sqlList = preg_split("/;[\r\n]+/", file_get_contents(ScriptConstant::KPIS_DIR));
if (empty($sqlList)) {
Tools::info("ERROR \n");
}
foreach ($sqlList as $sql) {
if ($this->ifcert_check->query($sql)) {
Tools::info("OK \n");
} else {
Tools::info("ERROR:%s\n", $this->ifcert_check->get_error());
}
}
}
MySQL存储过程简单介绍(推荐)
创建存储过程DEMO
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
-- 加载本次工作的开始点
DROP PROCEDURE IF EXISTS PROC_NAME;
DELIMITER //
REATE PROCEDURE PROC_NAME(IN parameter INT)
BEGIN
IF parameter=0 then
SELECT * FROM USER ORDER BY ID ASC;
ELSE
SELECT * FROM USER ORDER BY ID DESC;
END IF;
END//
DELIMITER ;

DROP PROCEDURE IF EXISTS getNum;
DELIMITER //
REATE PROCEDURE getNum(IN fid INT, OUT num INT)
BEGIN
SELECT COUNT(*) INTO num FROM USER WHERE id=fid;//into为赋值
END//
DELIMITER ;
调用存储过程
1
2
3
4
5
6
7
8
9
10
11
12
mysql> call PROC_NAME(0);
+----+------+------+------+
| id | name | pass | note |
+----+------+------+------+
| 1 | 1 | 1 | 1 |
| 2 | 2 | 2 | 2 |
| 3 | 3 | 3 | 3 |
| 4 | 4 | 4 | 4 |
| 5 | 5 | 5 | 5 |
+----+------+------+------+
5 rows in set (0.02 sec)
Query OK, 0 rows affected (0.02 sec)
存储过程体

存储过程体包含了在过程调用时必须执行的语句,例如:dml、ddl语句,IF-ELSE-END IF和while-do语句等
过程体格式:以begin开始,以end结束(可嵌套)

1
2
3
4
5
6
7
BEGIN
  BEGIN
    BEGIN
      statements;
    END
  END
END

存储过程的参数(IN, OUT, INOUT)
  • IN输入参数:表示调用者向过程传入值(传入值可以是字面量或变量)
  • OUT输出参数:表示过程向调用者传出值(可以返回多个值)(传出值只能是变量)
  • INOUT输入输出参数:既表示调用者向过程传入值,又表示过程向调用者传出值(值只能是变量)
IN输入参数
1
2
3
4
5
6
7
8
9
10
11
mysql> set @p_in=1;
Query OK, 0 rows affected (0.00 sec)
mysql> call getNum(1, @p_in);
Query OK, 1 row affected (0.00 sec)
mysql> select @p_in;
+-------+
| @p_in |
+-------+
| 1 |
+-------+
1 row in set (0.00 sec)
OUT输出参数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
mysql> set @p_in=1;
Query OK, 0 rows affected (0.00 sec)
mysql> set @p_out=2;
Query OK, 0 rows affected (0.00 sec)
mysql> call getNum(@p_out, @p_in);
Query OK, 1 row affected (0.00 sec)
mysql> select @p_out;
+--------+
| @p_out |
+--------+
| 2 |
+--------+
1 row in set (0.00 sec)
mysql> select @p_in;
+-------+
| @p_in |
+-------+
| 1 |
+-------+
1 row in set (0.00 sec)
INOUT输入参数
1
2
3
4
5
6
7
8
9
10
11
mysql> set @p_inout=1;
Query OK, 0 rows affected (0.00 sec)
mysql> call getNum(@p_inout, @p_inout);
Query OK, 1 row affected (0.00 sec)
mysql> select @p_inout;
+----------+
| @p_inout |
+----------+
| 1 |
+----------+
1 row in set (0.00 sec)
-------------本文结束感谢您的阅读-------------
坚持原创技术分享,您的支持将鼓励我继续创作!