mysql存储过程实例
要求: 查询某个库里面的所有的表,并将表里面的数据个数查询出来
原理: 使用游标循环查询出的结果
create procedure checkTbData()
begin
declare done tinyint default 0; -- 循环标记
declare $tableName varchar(5); -- 表名
declare cur cursor for select table_name from information_schema.tables where table_schema="dbName"; -- dbName 为库名
open cur; -- 打开游标
while done <> 1 do
fetch cur into $tableName;
set @cnt=0; -- 用户变量,必须用@开头
set @selectSql=concat("select count(1) into @cnt from ", $tableName); -- 动态sql, 因为表名不是固定的,无法直接使用sql,必须用动态sql
prepare stmt from @selectSql;
execute stmt;
insert into test_tableinfo values ($tableName, @cnt); -- 表test_tableinfo是自创建的,create table test_tableinfo (tablename varchar(50), cnt int)
end while;
close cur;
end
参考文件如下:
mysql存储过程在动态SQL内获取返回值
mysql存储过程语法及实例