Mysql:简单存储过程

2021/6/16 2:21:18

本文主要是介绍Mysql:简单存储过程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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

 



这篇关于Mysql:简单存储过程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程