MySQL IF else stored procedure syntax

Guys, I can’t find a solution to this problem, always giving a syntax error that I have ever tried ... can you just take a look at me, thanks

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 

I just want to check if the data exists in the table before I insert it, and I cannot use "On duplicate key update" because my primary key does not mean anything, its a table where I put 2-3 foreign keys. ...

+4
source share
2 answers

IF syntax is invalid. It should be:

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

However, if you never allow duplicate entries (MatchID, UserID) in your Betslips , why not define a UNIQUE in these columns, then use 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; 
+2
source
 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 
0
source

Source: https://habr.com/ru/post/1433167/


All Articles