I currently use the following SQL Stored Procedure to add patient information. The stored procedure checks if the patient already exist on the DB.
It is important to understand that the DB will store millions rows.
CREATE DEFINER=`rootuser`@`%` PROCEDURE `SP_patAddDetails`(
IN pFileNo VARCHAR(11),
IN pKey VARCHAR(1),
IN pTitle VARCHAR(15),
IN pFirstName VARCHAR(30),
IN pInitials VARCHAR(5),
IN pSurname VARCHAR(30),
IN pIDNo VARCHAR(15),
IN pDOB VARCHAR(10),
IN pGender VARCHAR(8),
IN pLanguage VARCHAR(15),
IN pOccupation VARCHAR(30),
IN pDependantCode VARCHAR(2),
IN pRelationship VARCHAR(15),
IN pMemNo VARCHAR(20)
)
BEGIN
START TRANSACTION;
INSERT INTO patDetails(patFileNo, patKey, patTitle, patFirstName, patInitials,
patSurname, patIDNo, patDOB, patGender, patLanguage,
patOccupation, patDependantCode, patRelationship,
patMemNo, patUpdated)
SELECT * FROM (SELECT pFileNo, pKey, pTitle, pFirstName, pInitials,
pSurname, pIDNo, pDOB, pGender, pLanguage,
pOccupation, pDependantCode, pRelationship,
pMemNo, now()) AS tmp
WHERE NOT EXISTS (
SELECT patFileNo, patKey, patTitle, patFirstName, patInitials, patSurname
FROM patDetails
WHERE patFileNo = pFileNo
AND patKey = pKey
AND patTitle = pTitle
AND patFirstName = pFirstName
AND patInitials = pInitials
AND patSurname = pSurname
)
LIMIT 1;
COMMIT;
SELECT LAST_INSERT_ID()
COMMIT;
END
There are three things I would like to know:
1. Can this MySQL procedure be improved to achieve better performance?
2. There are more information that needs to be stored apart from what is currently displayed in the SP and it is also stored in different tables e.g: Contact Info Table, Address Info Table, Medical Aid Table, etc.
Is there a way where I can test for a "false" (no duplicate entry) response, get the LAST_INSERT_ID to use as an Index when adding the other information,
3. Is it possible to put everything into a single Stored Procedure ?
What I have tried:
Stored Procedure as shown in question.