当前位置:Gxlcms > 数据库问题 > MySQL存储过程

MySQL存储过程

时间:2021-07-01 10:21:17 帮助过:10人阅读

-- 定义结束符为“$$”,mysql默认结束符为“;”
-- 意思是告诉mysql解释器,该段命令是否已经结束了,即标识一段命令起始和结束
delimiter $$

-- 创建存储过程
-- sp_char_split_inser:存储过程名称
-- strs:存储过程参数名称
-- in:表示该参数为输入参数;out:表示该参数为输出参数;inout:表示该参数为输入输出参数。不写时默认为in,即输入参数。
create procedure sp_char_split_inser(in strs text)
begin 
    declare i int default 0;
    declare leng int default 0;
    declare word char(1);
    
    -- 判断字符串是否为空或空字符串
    if(strs is not null && strs <> ‘‘) then 
        -- 获取字符串长度
        set leng = char_length(strs);
        -- 循环
        while i < leng do 
            -- 获取第一个字符
            set word=left(strs,1);
            if(word is not null && word <> ‘‘) then 
                -- 判断该条数据是否存在
                if not exists(select 1 from demo.charinfo where Hanzi=word limit 1) then 
                    -- 插入数据
                    insert into demo.charinfo(Hanzi) values(word);
                end if;
            end if;
            -- 截取除第一个字符之外的所有字符
            set strs=substring(strs,2);
            set i=i+1;
        end while;
    end if;
end;
-- 命令结束
$$
delimiter ;
技术分享图片

 

三、调用存储过程

-- 调用存储过程
set @s=‘测试文字‘;
call sp_char_split_inser(@s);
call sp_char_split_inser(‘测试一下‘);

 

四、删除存储过程

-- 删除存储过程
drop procedure sp_char_split_inser;
drop procedure if exists sp_char_split_inser;

 

MySQL存储过程

标签:demo   i+1   limit   mit   bst   tle   cal   src   告诉   

人气教程排行