最近在整理数据库的一些笔记,上传上来做个笔记,有不对的地方请指正.
存储过程
:
功能:使用sql语句
实现复杂的业务逻辑
Demo:
例1
create procedure p1() //p1:过程的名字;():必须有 不能加 ; 分号表示结束(什么都不要加)
begin
insert into users (account ,pwd) values ('zzc','123456');
select * from users;
end
call p1(); // 调用p1这个存储过程
例2
create procedure p2(x int)
begin
declare
y int;
#定义整形变量
set
y=x+1
; #赋值
select
y;
#查询并输出
end
set @m=4;
//定义变量
call p2(@m)
//调用p2
#例3 输出
create procedure p3( x int ,out y int)
begin
set y=x+1;
end
set @a=0;
call p3(6,@a) ;
select @a
#例4 判断
create procedure p4(x int)
begin
if
x >5 then
select '大于5' as da;
#末尾的;号不能省略
elseif
x < 5
then
select '小于5' as dd;
else
select '等于5';
end if;
end
call p4(1)
#循环
create procedure p5()
begin
declare
x int;
set
x=0;
while
x<5 do
set x=x+1;#x
end while
;
select x;
end
call p5()
#多路循环
create procedure p6(x int )
begin
case
when
x=5 then
select '=5' ;
when
x>5
then
select '>5' as de;
else
select '<5';
end case;
end
call p6(6)
#存入100000条数据
create table book(id int primary key auto_increment,title varchar(255))
create procedure p7()
begin
declare x int;
set x=0;
select now() as '开始时间';
start
transaction;--开启事务
while x<100000 do
insert into book (title) values (concat('aa',x)); //
concat连接字符串
set x=x+1;
end while;
commit
;
--提交事务
select now() as '结束时间';
end
call p7()
select (99999)