0

我想检查 db 表中特定记录的存在,如果存在则更新,如果不存在我想添加新记录

我正在使用存储过程来执行此操作,首先我进行更新语句并想检查它是否发生并返回 0 然后没有记录受更新语句影响,这意味着该记录不存在。

我这样做

DELIMITER //
CREATE PROCEDURE revokePrivilegeFromUsers(IN userId int(11),  IN privilegeId int(11), IN deletedBy int(11))

BEGIN
  DECLARE isExist int;

  isExist = update `user_privileges` set `mode` ='d' ,`updated_by` = deletedBy, `date_time_assigned` =  CURRENT_TIMESTAMP()  where `user_id`= userId and `privilege_id`=privilegeId;

 IF  isExist  == 0 THEN
      insert into `user_privileges`(`user_id`,`privilege_id`,`mode`,`date_time_assigned`,`updated_by`)values (userId ,privilegeId ,'d',CURRENT_TIMESTAMP(),deletedBy );

 END IF;


END //

DELIMITER ;

这个错误发生在我身上

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= update `user_privileges` set `mode` ='d' ,`updated_by` = deletedBy, `date_time' at line 6

mysql支持我的工作方式吗?

4

2 回答 2

1

我解决了问题,我有2个问题

  1. ROW_COUNT()用于获取插入、更新或删除语句中受影响的行数。
  2. 存储过程中的等于比较是 = 不是 ==

正确的存储过程是

DELIMITER //
CREATE PROCEDURE revokePrivilegeFromUsers(IN userId int(11),  IN privilegeId int(11), IN deletedBy int(11))

BEGIN
DECLARE count int default -1;

update `user_privileges` set `mode` ='d' ,`updated_by` = deletedBy, `date_time_assigned` =  CURRENT_TIMESTAMP()  where `user_id`= userId and `privilege_id`=privilegeId;
SELECT ROW_COUNT() into count ;
IF count  = 0 THEN
       insert into `user_privileges`(`user_id`,`privilege_id`,`mode`,`date_time_assigned`,`updated_by`)values (userId ,privilegeId ,'d',CURRENT_TIMESTAMP(),deletedBy );

END IF;
END //

DELIMITER ;
于 2012-04-23T09:11:14.530 回答
0

请改用 INSERT IGNORE 语句。我假设您的表具有 (user_id, privilege_id) 作为唯一键。

insert ignore into user_privileges (user_id,privilege_id,`mode,date_time_assigned,updated_by)
values (userId ,privilegeId ,'d',CURRENT_TIMESTAMP(),deletedBy )
on duplicate key update mode='d', date_time_assigned=now(),updated_by=deletedBy
于 2012-04-23T09:23:48.137 回答