Manohar Kumar
Manohar Kumar

Reputation: 55

MySQL store procedure Assign value to multiple variable from select statement

This is my Stored procedure . I have problem to assign value to Declared variable . When I Execute it, Insert and Update Command work fine but VALUE of Declared Variable remain 0; But I have some value in Database. How can i Do this Corectly.

BEGIN
DECLARE PaidFee INT DEFAULT 0; 
DECLARE DueFee INT DEFAULT 0; 
DECLARE CourseFee INT DEFAULT 0; 
INSERT INTO `creditdirectory`(`TypeID`, `PersonName`, `CreditBy`, `PersonID`, `ModeOfPayment`,`Details`,`Amount`,`CompanyID`) 
VALUES(1,PersonName,CreditBy, AddmissionID, ModeOfPayment, 'Installment', PaidAmount, 
 CompanyID); 
SELECT `CourseFee`,`PaidFee`,`DueFee` INTO CourseFee,PaidFee,DueFee FROM `studentcoursedetails` WHERE `ID`= CourseID; 
SET PaidFee = PaidFee + PaidAmount; 
SET DueFee = CourseFee - PaidFee; 
IF (NextDueDate !='') THEN 
UPDATE `studentcoursedetails` SET `PaidFee` = PaidFee, `DueFee` = DueFee, `DueDate` = NextDueDate WHERE `ID`= CourseID; 
ELSE 
UPDATE `studentcoursedetails` SET `PaidFee` = PaidFee, `DueFee` = DueFee, `DueDate` = NULL WHERE `ID` = CourseID; 
END IF; 
END

Upvotes: 4

Views: 4513

Answers (1)

Ivan Cachicatari
Ivan Cachicatari

Reputation: 4284

Don't use variables with same name of columns, the query will take preference on table column names.

A good idea is use variables with prefix:

BEGIN
    DECLARE p_PaidFee INT DEFAULT 0; 
    DECLARE p_DueFee INT DEFAULT 0; 
    DECLARE p_CourseFee INT DEFAULT 0; 
    INSERT INTO `creditdirectory`(`TypeID`, `PersonName`, `CreditBy`, `PersonID`, `ModeOfPayment`,`Details`,`Amount`,`CompanyID`) 
    VALUES(1,PersonName,CreditBy, AddmissionID, ModeOfPayment, 'Installment', PaidAmount, 
     CompanyID); 
    SELECT `CourseFee`,`PaidFee`,`DueFee` INTO p_CourseFee,p_PaidFee,p_DueFee FROM `studentcoursedetails` WHERE `ID`= CourseID; 
    SET p_PaidFee = p_PaidFee + PaidAmount; 
    SET p_DueFee = p_CourseFee - p_PaidFee; 
    IF (NextDueDate !='') THEN 
        UPDATE `studentcoursedetails` SET `PaidFee` = p_PaidFee, `DueFee` = p_DueFee, `DueDate` = NextDueDate WHERE `ID`= CourseID; 
    ELSE 
        UPDATE `studentcoursedetails` SET `PaidFee` = p_PaidFee, `DueFee` = p_DueFee, `DueDate` = NULL WHERE `ID` = CourseID; 
    END IF; 
END

Upvotes: 5

Related Questions