简体   繁体   English

mysql过程检查条目是否存在

[英]mysql procedure check if entry exists

i need a procedure to tell me if a entry exists so i know if i have permission. 我需要一个程序来告诉我是否存在条目,这样我才能知道我是否有权限。

    CREATE DEFINER=`root`@`localhost` procedure `checkPermission`(tbl varchar(50), id int, userid int, out b boolean)
begin
    set @q = concat("select idtblUsers into @rs from ", tbl, " where id", tbl, '=', id, ' && idtblUsers=', userid);

    prepare stmt1 FROM @q;
    EXECUTE stmt1;
    DEALLOCATE PREPARE stmt1;

    if @rs is not null then
        select true into b;
    else
        select false into b;
    end if;

END$$

call checkPermission('tblProjects', 2, 1, @b)

it always returns 1 in mysql-workbench even though it says there is no data (warning 1329) if there isn't a entry (i haven't got permission). 即使没有条目(我没有权限),即使它说没有数据(警告1329),它也总是在mysql-workbench中返回1。 but i would like true or false back in @b. 但是我想在@b中返回true或false。

Please have a try with this shortened version. 请尝试使用此简化版本。 The main problem is the DEFINER=root@localhost . 主要问题是DEFINER=root@localhost This executes the procedure with the rights that root@localhost has. 这将以root @ localhost拥有的权限执行该过程。 Since he most likely has every right there is, he won't run into permission restrictions. 由于他很可能拥有一切权利,因此他不会遇到权限限制。 So either you remove it and create the procedure with a restricted user, or you change it to DEFINER=restricted_user@host . 因此,要么删除它并使用受限用户创建过程,要么将其更改为DEFINER=restricted_user@host
exists() is also the better alternative, since it stops as soon as an entry was found. exists()也是更好的选择,因为它会在找到条目后立即停止。

CREATE procedure `checkPermission`(tbl varchar(50), id int, userid int, out b boolean)
begin
    set @q = concat("select exists(select 'whatever' into b from ", tbl, " where id", tbl, '=', id, ' && idtblUsers=', userid, ')');

    prepare stmt1 FROM @q;
    EXECUTE stmt1;
    DEALLOCATE PREPARE stmt1;

END$$

it nearly done the job but here is what works for me 它几乎完成了工作,但这对我有用

CREATE procedure `checkPermission`(tbl varchar(50), id int, userid int, out b boolean) 
begin
    set @q = concat("select exists( select idtblUsers from ", tbl, " where id", tbl, '=', id, ' && idtblUsers=', userid, ') into @b ');

    prepare stmt1 FROM @q;
    EXECUTE stmt1;
    DEALLOCATE PREPARE stmt1;

    select @b into b;
END$$

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM