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.存储函数必须遵守一条规则:不允许对调用本函数的表进行读和写的数据进行修改。
存储过程没有这个限制,但是如果存储过程在存储函数中调用就需要遵守这条规则。
转载于:https://my.oschina.net/fangfeiAI/blog/309194