(与模拟“如果不存在则创建用户”有关,但与语法错误不同。)
是否可以在 MySQL 中实现通用/动态添加用户(即模拟sp_adduser
其他 DBMS 中包含的系统过程)的功能?
MySQL 不支持以下if [not] exists
语法,请参阅http://bugs.mysql.com/bug.php?id=15287:
create user if not exists 'foo'@'%' identified by password 'bar';
它也不支持这个:
drop procedure if exists create_user_if_not_exists;
delimiter ||
create procedure create_user_if_not_exists
( sUser varchar(60),
sHost varchar(16),
sPassword varchar(255) )
begin
-- ensure user does not yet exist
if (select ifnull((select 1
from mysql.user
where User = sUser
and Host = sHost), 0) = 0) then
set @createUserText = concat('create user ''', sUser, '''@''', sHost, ''' identified by ''', sPassword, ''';');
prepare createUserStatement FROM @createUserText;
execute createUserStatement;
deallocate prepare createUserStatement;
end if;
end ||
delimiter ;
因为如果您尝试调用所述程序:
call create_user_if_not_exists ( 'foo', '%', 'bar' );
你收到了可爱的信息:
This command is not supported in the prepared statement protocol yet
以下工作,但显然不是特别可重用:
drop procedure if exists create_user_if_not_exists;
delimiter ||
create procedure create_user_if_not_exists
( )
begin
if (select ifnull((select 1
from mysql.user
where User = 'foo'
and Host = '%'), 0) = 0) then
create user 'foo'@'%' identified by password 'bar';
end if;
end ||
delimiter ;