MySQL存儲過程命令行
存儲過程code
定義存儲過程get
delimiter ;;
create procedure get_user_count()
beginit
select count(*) as user_count from sys_user;
end;;
delimiter;
關於分隔符變量
MySQL語句分隔符爲;,MySQL命令行程序也使用;做爲語句分隔符。若是經過命令行執行存儲過程會解釋存儲過程自身內的;字符,會使存儲過程當中的SQL出現語法錯誤。select
調用存儲過程語法
call get_user_count();
刪除存儲過程程序
drop procedure get_user_count;
使用參數im
參數中有outcall
-- 使用參數
-- in 傳遞到存儲過程
-- out 從存儲過程傳出
-- inout 對存儲過程傳入和傳出
delimiter ;;
create procedure get_count(
out user_count int(10), out role_count int(10), out dict_count int(10))
begin
select count(*) into user_count from sys_user; select count(*) into role_count from sys_role; select count(*) into dict_count from sys_dict;
end;;
delimiter ;
-- 調用
-- 全部MySQL變量都必須以@開始
-- 不能經過一個參數返回多個行和列
call get_count(@user_count, @role_count, @dict_count);
select @user_count, @role_count, @dict_count;
參數中有in有out
drop procedure if exists get_user_by_name;
delimiter ;;
create procedure get_user_by_name(
in user_name varchar(45), out user_id int(10))
begin
select id from sys_user where user_name = user_name limit 1 into user_id;
end;;
delimiter ;
-- 調用
call get_user_by_name('admin', @admin_id);
select @admin_id;
複雜一點的
-- comment 給存儲過程加註釋
-- 定義
delimiter ;;
create procedure insert_user(
in userName varchar(50), in defaultPass boolean, out userId int
) comment 'create user'
begin
declare pass varchar(50) default null; if defaultPass then set pass = '123456'; end if; insert into sys_user(user_name, user_password, create_time) values (userName, pass, now()); select LAST_INSERT_ID() into userId;
end;;
delimiter ;
-- 調用call insert_user('張三', false, @userId1);call insert_user('李四', true, @userId2);select @userId1, @userId2;select id, user_name, user_password, create_time from sys_user;