在mysql workbench中建立存儲過程

新手玩mysql stored procedure(存儲過程),期間遇到了不少麻煩,爲此貼出來,希望能爲也正在玩存儲過程的人提供一個demo。歡迎拍磚。

/*特別註明:下邊的SQL語句都是用test數據庫*/
use test;
create table user
(
    id int not null auto_increment primary key,
    userName varchar(30),
    userPsw varchar(20)
);
/*取消
create unique index user_id_index on user(id);
drop index user_id_index on user;
*/
use test;
create index user_name_index on user(userName);

use test;
/*登錄存儲過程*/
DELIMITER $$ 
create procedure `login`
(
in userName varchar(30) , 
in userPsw varchar(20) 
)
BEGIN
DECLARE selectname varchar(30);
DECLARE selectpsw varchar(20);
DECLARE result bool;
select user.userName,user.userPsw into selectname, selectpsw
    from user 
    where user.userName=userName and user.userPsw=userPsw;
    
IF selectname is not null and selectpsw is not null then
   set result=true;
ELSE set result=false;
end if;
select result;
end$$
DELIMITER ;

/*註冊存儲過程*/
DELIMITER $$
create PROCEDURE `regist`
(
/*out result bool;*/
in userName varchar(30),
in userPsw varchar(20)
)
BEGIN
DECLARE result bool;
DECLARE select_count int;

SELECT COUNT(user.userName) into select_count 
from user where user.userName=userName and user.userPsw=userPsw;
IF select_count=0 THEN
/*無重複則插入*/
INSERT INTO USER(user.userName,user.userPsw) 
values(userName,userPsw);
set result=true;
/*否則,不插入,返回插入失敗*/
ELSE set result=false;
/*用於臨時顯示結果,待註釋*/
SELECT RESULT;
END IF;

END$$
DELIMITER ;



use test;
drop procedure check_user;
drop procedure login;

use test;

insert into user(userName,userPsw) values
('ding','ding');
/*下邊是驗證存儲過程*/
use test;
call regist('ding','ding');
call login('admin','admin');

其實mysql 存儲過程並不難寫,關鍵是注意什麼時候要“;”什麼時候不要分號就OK了,否則會莫名其妙地編譯錯誤。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章