如果存在则更新,否则插入无效

2jcobegt  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(361)

我需要有关sql过程的帮助。我已经尽我所能试过了,但下面的程序不起作用,需要帮助为什么它不起作用,

CREATE PROCEDURE updateUser
     (IN ID INT(11), 
      name VARCHAR(100), 
      email VARCHAR(100), 
      role VARCHAR(9), 
      gender VARCHAR(6), 
      birthday VARCHAR(10), 
      classroom INT(11) )  

   SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

   BEGIN TRANSACTION;
       IF EXISTS (SELECT * FROM student WHERE userID = ID)
       BEGIN
           UPDATE tbl_users 
           SET userName = name, userEmail = email, userRole = role, 
               gender = gender, birthday = birthday 
           WHERE userID = ID;

           UPDATE student 
           SET classID = classroom 
           WHERE userID = ID;
       END
       ELSE
       BEGIN
           UPDATE tbl_users 
           SET userName = name, userEmail = email, userRole = role, 
               gender = gender, birthday = birthday 
           WHERE userID = ID;

           INSERT INTO student(classID, userID) 
           VALUES (classroom, ID);
       END

       COMMIT TRANSACTION;

以上更新到student查询和insert到查询都是单独工作的。但不是什么时候 IF EXISTS 已插入。

yacmzcpb

yacmzcpb1#

因为你使用的是mysql。试试下面的代码,看看是否有效,

CREATE PROCEDURE updateUser
     (IN ID INT(11), 
      name VARCHAR(100), 
      email VARCHAR(100), 
      role VARCHAR(9), 
      gender VARCHAR(6), 
      birthday VARCHAR(10), 
      classroom INT(11) )  

   BEGIN
       IF EXISTS (SELECT * FROM student WHERE userID = ID) THEN
       START TRANSACTION;
           UPDATE tbl_users 
           SET userName = name, userEmail = email, userRole = role, 
               gender = gender, birthday = birthday 
           WHERE userID = ID;

           UPDATE student 
           SET classID = classroom 
           WHERE userID = ID;
       COMMIT;
       ELSE
       START TRANSACTION;
           UPDATE tbl_users 
           SET userName = name, userEmail = email, userRole = role, 
               gender = gender, birthday = birthday 
           WHERE userID = ID;

           INSERT INTO student(classID, userID) 
           VALUES (classroom, ID);

       COMMIT;
       END IF;
   END;

相关问题