您的位置:首页 > 数据库 > MySQL

mysql存储过程和存储函数初步

2014-09-02 00:00 393 查看
摘要: mysql存储过程和存储函数初步学习

1.存储过程
delimiter $  //首先声明自定义结束符
create procedure show_times()  //存储过程名
begin
//需要执行的语句
select 'local time is',current_timestamp;
select 'UTC time is:',UTC_TIMESTAMP;
end $   //结束
调用存储过程: call show_times()$

2.带参数的存储过程
create procedure test_count(t int)
begin
select count(*) from t2 where t1=t;
end $
3.存储函数
delimiter $ ;
create function test_count2(t int)
returns int   //返回一个int类型
reads sql data
begin
return (select count(*)from t2 where t1=t);
end $
调用存储函数:select test_count2(1)$
4.---存储过程out参数
create procedure test_sum(out t2_sum int,out t1_sum int)
begin

select sum(t2) from t2 into t2_sum;
select sum(t1) from t2 into t1_sum;
end $
--调用
call test_sum(@sumT2,@sumT1)$
--取值
select @sumT2,@sumT1$
5.--触发器
create trigger bt1 before insert on t2
for each row
begin
set new.dt=current_timestamp;
if new.t1<0 then set new.t1=0;
elseif new.t1>100 then set new.t1=100;
end if;
end $
附表结构:
CREATE TABLE `t2` (
`t2` int(11) NOT NULL AUTO_INCREMENT,
`t1` int(11) DEFAULT NULL,
`dt` datetime DEFAULT NULL,
`name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`t2`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8

6.存储函数必须遵守一条规则:不允许对调用本函数的表进行读和写的数据进行修改。
存储过程没有这个限制,但是如果存储过程在存储函数中调用就需要遵守这条规则。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息