0

I have a Stored Procedure:

CREATE DEFINER=`root`@`localhost` PROCEDURE `InsertRaffleTicket`(IN userId BIGINT, IN raffleId BIGINT)
BEGIN
    INSERT INTO RaffleTicket(UserId, RaffleId)
    SELECT userId, raffleId
    FROM RaffleStatus rs
    WHERE rs.RaffleId = raffleId
    AND rs.SoldOut = 0;
END

How can I turn this into a function, that will return a value upon successful Insertion into the table?

I have tried:

CREATE DEFINER=`root`@`localhost` FUNCTION `addTicket`(UserId int, RaffleId int) RETURNS int(11)
BEGIN
    INSERT INTO RaffleTicket(UserId, RaffleId)
    SELECT userId, raffleId
    FROM RaffleStatus rs
    WHERE rs.RaffleId = raffleId
    AND rs.SoldOut = 0;
    return rs.SoldOut;
RETURN 1;
END

But it is giving me an Error 1109 Unkown table 'rs' in field list.

1 Answer 1

1
CREATE DEFINER=`root`@`localhost` FUNCTION `InsertRaffleTicket`(
userId BIGINT,
raffleId BIGINT
) RETURNS int
BEGIN

DECLARE retValue int;

select SoldOut into retValue from RaffleStatus where RaffleId = raffleId;

INSERT INTO RaffleTicket(UserId, RaffleId)
SELECT userId, raffleId
FROM RaffleStatus rs
WHERE rs.RaffleId = raffleId
AND rs.SoldOut = 0;

RETURN retValue;

END
Sign up to request clarification or add additional context in comments.

7 Comments

I might have updated while you were answering, but I keep getting Error 1054 Unkown column WbId when I put your example into my database.
I have updated my answer, please check now, I forgot to change variable name
That now adds the correct ticket. However it always returns 1. I need it to return the SoldOut value. So I know if SoldOut = 0, it added the ticket, if SoldOut = 1, it did not add the ticket.
Ive updated the code for the soldout output, please check now
Error 1415: Not allowed to return a result set from a function. I should add, RaffleStatus will return all raffle's that do not have all tickets sold for the raffle. IE: If RaffleId 1 and RaffleID 2 have 12 tickets in each raffle, and they have only sold 10 each, RaffleStatus will return both.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.