MySQL存储过程语法IF else

伙计们我找不到这个问题的解决方案,它总是给出语法错误我曾经尝试过……你能不能给我看一下,谢谢

create procedure SP_Insert(in MatchIDP int,in TipID int, in User int)
begin

if exists(
select BetSlipID from betslips where MatchID = MatchIDP and UserID = User)
(
   update Betslips set TipID = 2
)
else
(
   insert into Betslips (MatchID,TipID , UserID) value (MatchIDP,TipID,User)
)
end if
end

我只想在插入之前检查表中是否存在数据,并且我不能使用“在重复键更新”,因为我的主键并不意味着什么,它的表放在我的2-3个外键中….

最佳答案 您的IF语法不正确.它应该是:

delimiter ;;

create procedure SP_Insert(in MatchIDP int,in TipID int, in User int)
begin

if exists(
  select * from betslips where MatchID = MatchIDP and UserID = User
) then
  update Betslips set TipID = 2; -- where ?
else
  insert into Betslips (MatchID,TipID , UserID) values (MatchIDP, TipID, User);
end if;

end;;

但是,如果您永远不会允许Betslips中的重复(MatchID,UserID)条目,为什么不在这些列之间定义UNIQUE约束,然后使用INSERT ... ON DUPLICATE KEY UPDATE

ALTER TABLE Betslips ADD UNIQUE INDEX (MatchID, UserID);

INSERT INTO Betslips (MatchID, TipID, UserID) VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE TipID = 2;
点赞