mysql存储过程示例
CREATE DEFINER=`root`@`localhost` PROCEDURE `p_blog`(
in _organization_id int, -- 定义入参
in _page_index int,
in _page_size int
)
BEGIN
declare _organization_type int default 0; -- 定义变量
declare _children varchar(500);
start transaction; --开始事务(如果有更新多个表数据时可以使用事务)
select organization_type,children into _organization_type,_children from t_organization where id=_organization_id; -- 将查询结果赋值给变量
if _organization_type =0 then
set @sql = concat('select SQL_CALC_FOUND_ROWS * from t_blog where organization_id =',_organization_id,
' order by id desc limit ',(_page_index-1)*_page_size,',',_page_size); -- 定义和拼接动态sql语句,limit n,m 为分页用法,n表示从第几条记录开始(首条索引是0),m表示获取几条数据,-- SQL_CALC_FOUND_ROWS表示保存总记录数(后续会通过select found_rows() 这种方式来直接获取总记录数,提高了效率)
else
set @sql = concat('select SQL_CALC_FOUND_ROWS * from t_blog where organization_id in (0,',_children,')',
' order by id desc limit ',(_page_index-1)*_page_size,',',_page_size);
end if;
PREPARE stmt_name FROM @sql; -- 预处理动态sql语句
EXECUTE stmt_name; -- 执行预处理语句
DEALLOCATE PREPARE stmt_name; --释放资源
select found_rows() as total,_page_index as page_index; --
commit; -- 提交事务(如果有更新多个表数据时可以使用事务)
END