简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM