什么是存储过程:
简单的说,就是一组SQL语句集,功能强大,可以实现一些比较复杂的逻辑功能,类似于JAVA语言中的方法;
ps:存储过程跟触发器有点类似,都是一组SQL集,但是存储过程是主动调用的,且功能比触发器更加强大,触发器是某件事触发后自动调用;
有输入输出参数,可以声明变量,有if/else, case,while等控制语句,通过编写存储过程,可以实现复杂的逻辑功能;
函数的普遍特性:模块化,封装,代码复用;
速度快,只有首次执行需经过编译和优化步骤,后续被调用可以直接执行,省去以上步骤;
创建一个简单的存储过程:
BEGIN
#Routine body goes here...
DECLARE record_id bigint DEFAULT 100000;#订单id
DECLARE open_house_id bigint default 1000000;#房源id
DECLARE order_no bigint DEFAULT 2016010200001; # 订单号
DECLARE cus_id int DEFAULT 10000; #客户id
DECLARE i int DEFAULT 0;
while i < 800000 DO
insert into t__record values(record_id,order_no,6900,100000,open_house_id,cus_id,1,1,700,null,'2017-12-01
10:40:20',5100,null,'2017-12-01 10:40:20',1);
set record_id = record_id+1;
set i = i+1;
set order_no = order_no+1;
set cus_id = cus_id+1;
end WHILE;
END
存储过程中控制语句:
IF语句:
CREATE PROCEDURE `proc_if`(IN type int) BEGIN #Routine body goes here... DECLARE c varchar(500); IF type = 0 THEN set c = 'param is 0'; ELSEIF type = 1 THEN set c = 'param is 1'; ELSE set c = 'param is others, not 0 or 1'; END IF; select c; END
CASE语句:
CREATE PROCEDURE `proc_case`(IN type int) BEGIN #Routine body goes here... DECLARE c varchar(500); CASE type WHEN 0 THEN set c = 'param is 0'; WHEN 1 THEN set c = 'param is 1'; ELSE set c = 'param is others, not 0 or 1'; END CASE; select c; END
循环while语句:
CREATE PROCEDURE `proc_while`(IN n int) BEGIN #Routine body goes here... DECLARE i int; DECLARE s int; SET i = 0; SET s = 0; WHILE i <= n DO set s = s + i; set i = i + 1; END WHILE; SELECT s; END