mysql存储过程

来源:互联网 发布:apache ddos ip 大量 编辑:程序博客网 时间:2024/06/05 23:03

此存储过程实例,主要注意 在存储过程中 if 语句的使用,已经如果存在则不添加 not exists的使用,
insert into table_name(column1) select column1 from table_name2
where colunm2=’condition1’
and not exists (select 1 from table_name2 where table_name2.column1=table_name.column1)

DELIMITER $$CREATE PROCEDURE `sp_create_empty_account`(    p_cellphone varchar(20),            p_channel_code varchar(50),         out p_return varchar(100)           )BEGIN    declare v_user_id ,v_account_id,v_channel_id,v_channel_account_id bigint ;    declare v_is_main_channel bit;    DECLARE exit HANDLER FOR SQLEXCEPTION    begin         ROLLBACK;        set p_return='fail';     end;    set p_return="";    select c_channel_id,c_is_default into v_channel_id,v_is_main_channel from t_channel     where c_code=p_channel_code    and c_type=0 and c_status=1;     if (v_channel_id>0 && exists (select 1 from t_user where c_cellphone =p_cellphone))    then        select c_user_id into v_user_id        from t_user where c_cellphone=p_cellphone;        ** set autocommit=0; **        start transaction;        INSERT INTO  t_account(`c_user_id`) select v_user_id         from dual        where not exists (select 1 from t_account where c_user_id=v_user_id);        select c_account_id into v_account_id from t_account where c_user_id=v_user_id;        if (v_account_id>0 && not exists (select 1 from t_channel_account                 where c_account_id=v_account_id and c_channel_id=v_channel_id))        then            insert into t_channel_account (c_account_id,c_channel_id,c_is_active)            values(v_account_id,v_channel_id,v_is_main_channel);            if v_is_main_channel=b'1'            then                select c_channel_account_id into v_channel_account_id                from t_channel_account                 where c_account_id=v_account_id and c_is_active=b'1';                update t_account set c_channel_account_id=v_channel_account_id                where c_account_id=v_account_id;            end if;        end if;        commit;        set p_return="success";    else        set p_return="not found user or channel";    end if;END
0 0
原创粉丝点击