如何在存储过程中编写多个查询

时间:2017-02-06 10:41:04

标签: php mysql stored-procedures

我想要做的是当用户角色更改为1或从1删除所有他在ForumManager表中的条目时IsDirect值为0或者如果其值更改为1则我需要将人员条目插入到ForumManager表中所有ForumID。

但是为了插入它,我必须再运行1个查询来获取ForumID并在循环中插入ForumManager。

到目前为止我尝试的是不完整的,可能不正确或正确的方式我不知道如何在存储过程中运行循环。

delimiter //
CREATE PROCEDURE update_forum_admin (IN user_id INT, IN previous_role INT,IN new_role INT)
BEGIN
if(previous_role == 1)
{
    DELETE ForumManager WHERE UserID=user_id AND IsDirect=0
}
elseif(new_role == 1) 
{
    SELECT ForumID FROM Forum
    INSERT ForumManager (ForumID,UserID,IsDirect) VALUES (forum_id,user_id,0)
}
END//
delimiter ;

3 个答案:

答案 0 :(得分:1)

如果在Forum表中有一个列名user_id,则将参数从user_id重命名为userId。

    sftp> mput /export/test-n-20170203.done
    test-n-20170203.done | 28B | 330B/s | TOC: 00:00:00
    sftp> exit

    On the receiving server B, .done file details are as follows
      Size: 28              Blocks: 2          IO Block: 8192   regular file
    Device: 980c75bh/159434587d     Inode: 15595212    Links: 1
    Access: (0644/-rw-r--r--)  Uid: (2000002519/u)   Gid: (10002004/   m)
    Access: 2017-02-06 01:35:46.752507000 -0500
    Modify: 2017-02-06 01:30:13.782729000 -0500
    Change: 2017-02-06 01:35:46.759508000 -0500

答案 1 :(得分:0)

你可以使用ID_forum声明一个coursor,并在下面的elseif语句中迭代它(如果你有问题要实现它,请使用伪代码):

      CREATE PROCEDURE update_forum_admin (IN user_id INT, IN previous_role  INT,IN     new_role INT)
        BEGIN
        CURSOR CUR_ID_FORUM
        IS
           SELECT ForumID FROM Forum;

    if(previous_role == 1)
    {
        DELETE ForumManager WHERE UserID=user_id AND IsDirect=0
    }
    elseif(new_role == 1) 
    {
          FOR REC_ID_FORUM IN CUR_ID_FORUM
          LOOP
            INSERT ForumManager (ForumID,UserID,IsDirect) VALUES    (REC_ID_FORUM,user_id,0)
          END LOOP;   
    }
    END update_forum_admin  ;

答案 2 :(得分:0)

它安静了一段时间,但是Mohit可以通过修改如下代码来摆脱语法错误

CREATE PROCEDURE update_forum_admin (IN user_id INT, IN previous_role INT,IN new_role INT)
BEGIN
if(previous_role = 1)
BEGIN
    DELETE ForumManager WHERE UserID=user_id AND IsDirect=0
END
if(new_role = 1) 
BEGIN
    SELECT ForumID FROM Forum
    INSERT ForumManager (ForumID,UserID,IsDirect) VALUES (forum_id,user_id,0)
END

我还可以看到,当您从ForumManager删除用户时,您并未为特定论坛删除。可能是您只有一个论坛,如果是这种情况,则从论坛表中获取前1个论坛ID