MySQL StoredProcedure Variable set from select with parameters as conditions - mysql

So I'm trying to get the PatientID (primary key, not null, autoincrement) from a patient that I added to the database earlier within a stored procedure using the parameters for FName and LName passed in in my select statement to set the variable, but I'm getting a syntax error. So any help as to why the syntax is failing would be appreciated.
Here's the relevant code, pFName and pLName are parameters passed into the stored procedure.
DECLARE pPolicyHolder INT;
SET pPolicyHolder = (SELECT PatientID FROM Patient WHERE Fname = pFName AND LName = pLName);
And here's the entire procedure. I realize it's probably not the best/cleanest way to do this, but the way the tables are set up is that the MedicalHistory needs to be added before the Patient can be added, and the Patient must be added before the PatientInsurance can be added because of Foreign Key constraints.
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 ;
The error:
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

You need to declare variables at the beginning of your procedure, not in the middle.
CREATE PROCEDURE AddNewPatient(...)
BEGIN
DECLARE pPolicyHolder INT; <------declare here
START TRANSACTION;
...
COMMIT;
SET pPolicyHolder = (SELECT PatientID FROM Patient WHERE Fname = pFName AND
LName = pLName);
...

Related

ERROR 1064 in mysql, can anybody check what is the error?

CREATE PROCEDURE insert_user(in uname varchar(20),in gender varchar(20),in email varchar(20),in phone varchar(20),in pword varchar(20),in city varchar(20))
BEGIN
DECLARE finished integer default 0;
Declare cnt integer default 0;
declare id integer;
DECLARE c_cur cursor for select user_id from user;
DECLARE CONTINUE HANDLE FOR NOT FOUND SET finished = 1;
open c_cur;
ins_user: loop
fetch c_cur into id;
IF finished = 1 THEN
LEAVE ins_user;
end if;
cnt:=id;
end loop ins_user;
cnt:=cnt+1;
insert into user
values(cnt,uname,email,phone,city,pword,gender);
END;
Am getting the error #1064 - 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 'HANDLE FOR NOT FOUND SET finished = 1; open c_cur; ins_user: loop fetch ' at line 7
i am not sure where its getting wrong
Set the Delimiter to something else, other than ;, for eg: $$. This will allow the parser to treat the whole create statement as one.
At the end, redefine the Delimiter back to ;
user is a keyword in MySQL. It is better to rename your table to something else, or use backticks around it.
There is a typo; it should be HANDLER not HANDLE
Try:
DELIMITER $$
DROP PROCEDURE IF EXISTS insert_user $$
CREATE PROCEDURE insert_user(in uname varchar(20),
in gender varchar(20),
in email varchar(20),
in phone varchar(20),
in pword varchar(20),
in city varchar(20))
BEGIN
DECLARE finished INT DEFAULT 0;
Declare cnt INT DEFAULT 0;
declare id INT;
DECLARE c_cur CURSOR FOR select user_id from `user`;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
open c_cur;
ins_user: loop
fetch c_cur into id;
IF finished = 1 THEN
LEAVE ins_user;
end if;
SET cnt:=id; -- set was missing here
end loop ins_user;
SET cnt:=cnt+1; -- set was missing here
insert into `user`
values(cnt,uname,email,phone,city,pword,gender);
END $$
DELIMITER ;

phpmyadmin wamp mysql cannot declare variable in procedure

I have unsloved problem when I try to create a stored procedure following code below
but it shows error
#1064 - 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 at line 5
and this is my code Thanks for advice.
CREATE DEFINER=root#localhost PROCEDURE item_page_insert(IN cid INT, IN it_title VARCHAR(200), IN tumbnail VARCHAR(300), IN publish_date DATE, IN cover_set VARCHAR(20), IN pcontent TEXT, IN status INT) MODIFIES SQL DATA
BEGIN
DECLARE mpid INT;
SELECT max(pid)+1 INTO mpid
FROM tbpage;
INSERT INTO tbite(cid, pid, it_title, tumbnail, publish_date, cover_set)
VALUES(cid,
mpid,
it_title,
tumbnail,
publish_date,
cover_set);
INSERT INTO tbpage(pid, pcontent, set_date, status)
VALUES(mpid,
pcontent,
now(),
status); END;
DELIMITER ;
it should be
DECLARE mpid AS INT;
try that one

MySQL 5.6 Declare Issue

Let's see if I can edit this and put the whole procedure in.
I am trying to convert an Oracle database to MySQL. I have all the tables, keys, indexes, and views converted. I now need to convert a stored procedure to MySQL.
I have most of it done, and there is only one hang up on my code:
set dns1_tmp = X.X.X.X;
SET dns2_tmp = X.X.X.X;
This gives me an error of 1064 Syntax Error: Missing semicolon
I have tested the rest of my procedure, and it works fine. It creates it, runs it, and retrieves data from it, but only if I remove those two lines.
Any ideas on what I can do?
Whole stored procedure:
DELIMITER //
USE `TEST`//
DROP PROCEDURE IF EXISTS `proc_IN`//
CREATE DEFINER=`root`#`localhost` PROCEDURE `proc_IN`
(IN DNIS VARCHAR(20),
IN MSISDN VARCHAR(20),
IN AVPAIR1 VARCHAR(20),
IN AVPAIR2 VARCHAR(20),
IN GROUPID VARCHAR(20),
OUT DNS1 VARCHAR(15),
OUT DNS2 VARCHAR(15),
OUT AUTHSTAT VARCHAR(100))
BEGIN
declare dns1_tmp varchar(15);
declare dns2_tmp varchar(15);
set dns1_tmp = X.X.X.X;
SET dns2_tmp = X.X.X.X;
DECLARE avpair1_tmp varchar(15);
DECLARE avpair2_tmp varchar(15);
DECLARE grpid_tmp varchar(15);
DECLARE C_USER CURSOR FOR SELECT AVPAIR1, AVPAIR2, DNS1, DNS2, GROUPID FROM GRP, ALLMEMBER WHERE ALLMEMBER.GROUPID=GRP.GROUPID
UNION
SELECT AVPAIR1, AVPAIR2, DNS1, DNS2, GROUPID FROM GRP;
OPEN C_USER;
FETCH C_USER INTO AVPAIR1, AVPAIR2, DNS1, DNS2, GROUPID;
LOOP
FETCH C_USER INTO avpair1_tmp, avpair2_tmp, dns1_tmp, dns2_tmp, grpid_tmp;
INSERT INTO duplog VALUES(DNIS, MSISDN, avpair1_tmp, avpair2_tmp, dns1_tmp,dns2_tmp, grpid_tmp, SYSDATE);
END LOOP;
IF C_USER%ROWCOUNT > 1 THEN
INSERT INTO duplog VALUES(DNIS, MSISDN, AVPAIR1, AVPAIR2, DNS1,DNS2, GROUPID, SYSDATE);
SET AUTHSTAT := 'ok';
elseif C_USER%ROWCOUNT = 1 THEN
SET AUTHSTAT := 'ok';
ELSE
SET AUTHSTAT := NULL;
END IF;
CLOSE C_USER;
COMMIT;
END //
DELIMITER ;

mysql insert statement as a variable [duplicate]

This question already has answers here:
How To have Dynamic SQL in MySQL Stored Procedure
(3 answers)
Closed 8 years ago.
is it possible to set a variable to an insert statement in a stored procedure?
Something like:
set variable1 = insert into table(field1, field2, field3) values(val1, val2, variable2);
If so, how should it be written?
I keep throwing errors and documentation in the wild is inconclusive.
I was going for brevity but the entire procedure is thus:
-- --------------------------------------------------------------------------------
-- Routine DDL
-- Note: comments before and after the routine body will not be stored by the server
-- --------------------------------------------------------------------------------
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `new_accession`(in barcode int, in accepted varchar(11), in wt float(11,2), in wtunit varchar(3),in draw date, in chist varchar(256), in ghist varchar(256), in meds varchar(256), in diffdiag varchar(256),in diseasesus varchar(256),in volume int, in facility int, in patient int, in employ int, in compromised int, in receiving int, in test int)
BEGIN
declare accessionId int;
declare accessionTest int;
declare tkInsert varchar(256);
declare hptInsert varchar(256);
declare calInsert varchar(256);
declare pthInsert varchar(256);
declare vitdtkInsert varchar(256);
declare cnpInsert varchar(256);
if wtunit = 'lb' then set wt = convertLbKg(wt);
end if;
INSERT INTO accession(barcode_accession,accepted_accession,weight_accession,req_weight_units,draw_date_accession,cancer_history_accession,general_history_accession,medication_accession,differential_diagnosis_accession,disease_suspect_accession,volume_accession,facility_doctor_index_id_facility_doctor_index,patient_id_patient,employee_id_employee,accession_compromised_id_accession_compromised,receiving_id,accession_typeof_id_accession_typeof)
VALUES (barcode,accepted,wt,wtunit,draw,chist,ghist,meds,diffdiag,diseasesus,volume,facility,patient,employ,compromised,receiving,1);
set accessionId = last_insert_id();
set tkInsert = insert into pending(accession_facility_index,reagent_type,`status`)values(accessionId,1,'Pending');
set hptInsert = insert into pending(accession_facility_index,reagent_type,`status`)values(accessionId,2,'Pending');
set calInsert = insert into pending(accession_facility_index,reagent_type,`status`)values(accessionId,3,'Pending');
set pthInsert = insert into pending(accession_facility_index,reagent_type,`status`)values(accessionId,4,'Pending');
if test = 1 then tkInsert,calInsert;
elseif test =2 the hptInsert,pthInsert;
else pthInsert;
end if;
END
It is not very clear what you want but if your goal is to store insert's outcome (affected rows) you could use ROW_COUNT().
ROW_COUNT() returns the number of rows changed, deleted, or inserted
by the last statement if it was an UPDATE, DELETE, or INSERT.
For other statements, the value may not be meaningful.
For example:
variable1 = (select ROW_COUNT());
I think you're looking for prepared statements.
PREPARE tkInsert FROM CONCAT("insert into pending(accession_facility_index,reagent_type,`status`)values(?, 1,'Pending')";
Then you execute it with:
EXECUTE tkInsert USING accessionId;

Stored Procedure issue

I am new to sql and most of my training is in MSSQL, however I am taking a class in MYSQL. I have a stored procedure that is giving me an issue. I have the delimiter set to //.
CREATE PROCEDURE AddComment
(
name varchar(50),
emailAddress varchar(50),
Comments text
)
BEGIN
DECLARE ComName varchar(50);
DECLARE ComID int;
SELECT name into ComName;
SELECT ID into ComID from Commenters WHERE names = ComName;
if ComID = NULL
BEGIN
INSERT INTO COMMENTERS ('names', 'emailAddresses') values (name, emailAddress);
SELECT ID into ComID from Commenters WHERE names = ComName;
END
INSERT INTO COMMENTS ('commentersID', 'Comments') values (ComID, Comments);
END;
//
EDIT
This is what I have now:
CREATE PROCEDURE AddComment
(
Username varchar(50),
UseremailAddress varchar(50),
UserComment text
)
BEGIN
DECLARE ComName varchar(50);
DECLARE ComID int;
SELECT Username into ComName;
SELECT ID into ComID from Commenters WHERE names = ComName;
if ComID = NULL
BEGIN
INSERT INTO COMMENTERS(names,emailAddresses) values (Username, UseremailAddress);
SELECT ID into ComID from Commenters WHERE names = ComName;
END
INSERT INTO COMMENTS(commentersID, Comments) values (ComID, UserComment);
END;
//
And the error I am getting is:
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 'BEGIN INSERT INT
O COMMENTERS(names, emailAddresses) values (Username, Useremail' at line 1
Any Ideas?
You are coding column names and values reversed in you insert statements.
It should be
INSERT INTO COMMENTERS (name, emailAddress) values ('names', 'emailAddresses') ;