mysq进阶

学习资料:

官方文档:http://dev.mysql.com/doc/refman/5.0/en/tutorial.html

1.存储过程:

优点:业务逻辑封装在存储过程中,容易维护,执行效率也高。

缺点:不同的数据库功能函数等不一样,移植的时候需要改动。

create procedure 存储过程名字()
(
   [in|out|inout] 参数 datatype
)
begin
   MySQL 语句;
end;

栗子:

DELIMITER//
create procedure pr_add
(
   a int,
   b int
)
begin
   declare c int; //后加DEFAULT赋默认值,SET 赋值,存储过程的参数不能指定默认值
   if a is null then
      set a = 0;
   end if;
   if b is null then
      set b = 0;
   end if;
   set c = a + b;
   select c as sum;
END//

注意:与sqlserver不同的是,没有加DELIMITER// 和 END//无法执行

调用存储过程:

call pr_add(10, 20);

或者

set @a = 10;
set @b = 20;

call pr_add(@a, @b);

关键字:

IF THEN、ELSEIF、ELSE、END IF

name:LOOP 、END LOOP name

WHILE DO、END WHILE

REPEAT、UNTILL ... END REPEAT

2.自定义函数

mysql>DEMILITER $$

 3.

自定义触发器:当一阵表插入数据时,另一张表同步更新,并且自增id。

DROP TRIGGER IF EXISTS t_afterinsert_on_kd_files;
CREATE TRIGGER t_afterinsert_on_kd_files
AFTER INSERT ON kd_files
FOR EACH ROW
BEGIN
if new.in_recycle=0 then
SET @VAR= (select max(id)+1 from kd_files_es)+1;
#insert into kd_files_es_test(file_id,uid,file_name,file_ext,kf_id,file_size,mtime) select new.file_id,new.uid,new.file_name,new.file_ext,new.kf_id,new.file_size,new.mtime FROM kd_files LIMIT 1;
INSERT into kd_files_es set id=@VAR,file_id=new.file_id,uid=new.uid,file_name=new.file_name,file_ext=new.file_ext,kf_id=new.kf_id,file_size=new.file_size,mtime=new.mtime,tag=1;
end IF;
END;

原文地址:https://www.cnblogs.com/flyingbee6/p/5248494.html