没想到这就是最后一次实验了。
这是用于指定语句分隔符的特殊命令
默认情况下,MySQL使用分号(;)作为语句的结束符。然而,当我们需要定义存储过程、触发器或函数等包含多条SQL语句的对象时,分号会被误认为语句结束,导致出现语法错误。
为了解决这个问题,可以使用DELIMITER命令将分号(;)替换为其他字符作为语句分隔符,以便在创建存储过程、触发器或函数等对象时,正确处理多条SQL语句。
用法:DELIMITER // 内容 DELIMITER ;
因为要调用,所以类似于英雄主动技能
创建存储过程:create procedure 名字() begin 具体内容 end;
有参数:
create procedure 名字( in 参数1 int, in 参数2 int ) begin 具体内容 end;
删除存储过程:
drop procedure 名字;
调用存储过程
call 名字
不需要调用,类似于被动技能
推荐文章:文章
不得不说,你如果想要狠狠搞清楚触发器怎么用的话,我还是推荐你看推荐文章
创建触发器:create trigger 名字 前/后 触发方式 表名 for each row begin ·········· end;
删除触发器:
drop trigger 名字;
student表:
student1表:
course表:
sc表:
teacher表:
DELIMITER //
create procedure GetStudentCount()
begin
declare studentCount int; #定义局部变量
select count(*) into studentCount from student; #数行数
# select count(*) into a 的意思是将count(*)的值赋给a
select studentCount AS StudentCount;
end //
DELIMITER ;
调用:
call GetStudentCount();
delimiter //
create procedure CompareStudentAge(
in student1_num int,
in student2_num int
) #我使用的参数是学生编号,你也可以尝试不同的写法
begin
declare result int;
declare age1 int;
declare age2 int;
select Sage into age1 from student where Sno = student1_num;
select Sage into age2 from student where Sno = student2_num; #进行查询操作
if age1 > age2 then
set result = 1;
else
set result = 0;
end if;
select result as CompareResult;
end //
delimiter ;
调用:
call CompareStudentAge(2008001,2008003);
delimiter //
create trigger delete_student_sc
before delete on student
for each row
begin
delete from sc where Sno = OLD.Sno;
end;
delimiter ;
触发:
delete from student where Sno = 2008002;
delimiter //
create trigger add_student_st1
after insert on student
for each row
begin
insert into student1 (Sno, Sname, Ssex, Sage, Sdept)
VALUES (new.Sno, new.Sname, new.Ssex, new.Sage, new.Sdept);
end;
delimiter ;
触发:
insert into student(sno, sname, ssex, sage, sdept) VALUES ('2008006','杨过','男','19','IS');
delimiter //
create trigger teacher_income
before insert on teacher
for each row
begin
if new.Income < 4000 then
set new.Income = 4000;
end if;
end;
delimiter ;
drop trigger teacher_income;