MySQL存储过程变量从select中设置,参数作为条件

时间:2013-04-14 15:17:08

标签: mysql variables stored-procedures

所以我试图从我在select语句中传入的FName和LName参数设置的存储过程中早先添加到数据库的患者那里获取PatientID(主键,而不是null,自动增量)变量,但我得到一个语法错误。因此,对于语法失败原因的任何帮助都将不胜感激。

这是相关代码,pFName和pLName是传递给存储过程的参数。

DECLARE pPolicyHolder INT;
SET pPolicyHolder = (SELECT PatientID FROM Patient WHERE Fname = pFName AND LName = pLName);

这是整个程序。我意识到这可能不是最好/最干净的方法,但是表格的设置方式是需要在添加患者之前添加MedicalHistory,并且必须在添加PatientInsurance之前添加患者,因为外键约束。

DELIMITER //
CREATE PROCEDURE AddNewPatient(
    IN pAllergies TEXT, IN pMedications TEXT, IN pExistingConditions TEXT, IN pMisc       
    TEXT, IN pFName VARCHAR(30), IN pLName VARCHAR(45), IN pGender CHAR(1), IN pDOB 
    DATE, IN pSSN DOUBLE, IN pMedicalHistory INT, IN pPrimaryPhysician INT, IN 
    pInsuranceCompany INT, IN pCoPay INT)
BEGIN
    START TRANSACTION;
         INSERT INTO MedicalHistory(Allergies, Medications, ExistingConditions, Misc) 
         VALUES(pAllergies, pMedications, pExistingConditions, pMisc);
    COMMIT;
        START TRANSACTION;
              INSERT INTO Patient(FName, LName, Gender, DOB, SSN, 
              MedicalHistory,PrimaryPhysician) VALUES(pFName, 
              LName,pGender,pDOB,pSSN,pMedicalHistory,pPrimaryPhysician);
        COMMIT;

       DECLARE pPolicyHolder INT;
       SET pPolicyHolder = (SELECT PatientID FROM Patient WHERE Fname = pFName AND 
                            LName = pLName);
    START TRANSACTION;
       INSERT INTO PatientInsurance(PolicyHolder, InsuranceCompany, CoPay) 
       VALUES(pPolicyHolder, pInsuranceCompany, pCoPay);
    COMMIT;
    END //
DELIMITER ;

错误:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE pPolicyHolder INT;
   SELECT PatientID into pPolicyHolder FROM Patient W' at line 15

1 个答案:

答案 0 :(得分:2)

您需要在程序开始时声明变量,而不是在中间。

CREATE PROCEDURE AddNewPatient(...)
BEGIN
   DECLARE pPolicyHolder INT;  <------declare here

   START TRANSACTION;
   ...
   COMMIT;

   SET pPolicyHolder = (SELECT PatientID FROM Patient WHERE Fname = pFName AND 
                        LName = pLName);
   ...