MySQL存储过程语法IF else

时间:2012-09-08 20:02:52

标签: mysql stored-procedures

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

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

我只是想在插入之前检查表中是否存在数据,并且我不能使用“On duplicate key update”,因为我的主键并不意味着什么,我的表放在2-3个外键中。 ...

2 个答案:

答案 0 :(得分:2)

您的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;;

但是,如果您永远不会在(MatchID, UserID)中允许重复的Betslips条目,为什么不在这些列中定义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;

答案 1 :(得分:0)

CREATE PROCEDURE SP_Insert (IN MatchIDP INT, IN TipID INT, IN USER INT)
BEGIN
        DECLARE existing INT DEFAULT NULL;

        SELECT BetSlipID
        INTO   existing
        FROM   betslips
        WHERE  MatchID = MatchIDP
        AND    UserID = USER;

        IF existing is not null THEN
            UPDATE Betslips SET TipID = 2;
        ELSE
            INSERT INTO Betslips (MatchID, TipID, UserID)
            VALUES (MatchIDP, TipID, USER);
        END IF;

END