Search code examples
mysqlstored-proceduresmethod-call

I keep getting zeros when I call a procedure that should be calling data I know exists


I'm trying to write a stored procedure in MySQL and then call it back, and I have to submit a screenshot of the procedure returning a correct response. The code for storing the procedure seems to work fine (no errors, at least), but when I run the CALL function it returns 0.00 no matter which number I put in for @column3. My instructor thinks the issue is stating the OUT as AmountDue before I define the variable at the very top, but I couldn't figure out another way to have an input for @column3 in the CALL function without the IN/OUT constraints. I'm very new at this, obviously, so forgive me if I'm missing something obvious...Anyone got any ideas?

Also, I don't need any help with building the database, adding tables, anything like that. The database exists and functions appropriately. Only need help on storing the procedure and calling it back. Thanks.

delimiter //

DROP PROCEDURE IF EXISTS GetAmountDue;

CREATE PROCEDURE GetAmountDue(IN order_num INT, OUT AmountDue DECIMAL(10,2))
BEGIN
DECLARE AmountDue DECIMAL(10,2) DEFAULT 0;

SELECT COST
INTO @AmountDue
FROM cake_shape
INNER JOIN ll_cakery.order
ON cake_shape.shape_id=order.shape_id
WHERE order_num=@order_num;

SELECT AmountDue;
END//

delimiter ;

CALL GetAmountDue('113',@AmountDue);
  • order_num is a column with individual 3-character integer data values
  • cost is a column with individual decimal(10,2) data values
  • cake_shape is a table
  • ll_cakery.order is a table (that doesn't work quite right because mysql has a command ORDER so I have to give the schema name)
  • shape_id is a column, only used in the procedure for the join
  • in the CALL function, @order_num=113

Solution

  • You are passinf a string not an int

    You don't compare column 3 with column1

    Last you have to set the output variable with the data ou get from the select

    Last never name variables like columns name, that brings only problems

    CREATE tABLE table1 ( COST DECIMAL(19,2),column2 int, column3 int)
    
    INSERT INTO table1 VALUES (10.2,1,1),(10.2,1,1)
    
    CREATE TABLE table2 (column2 int)
    
    INSERT INTO table2 VALUES (1)
    
    CREATE PROCEDURE GetAmountDue(IN _column1 INT, OUT _AmountDue DECIMAL(10,2))
    BEGIN
    
    
    SELECT SUM(COST)
    INTO @AmountDue
    FROM table1
    INNER JOIN table2
    ON table1.column2=table2.column2
    WHERE column3=_column1;
    
    SET _AmountDue := @AmountDue;
    END
    
    CALL GetAmountDue(1,@AmountDue);
    
    SELECT @AmountDue
    
    | @AmountDue |
    | ---------: |
    |      20.40 |
    

    db<>fiddle here