Patient Information Retrieval π¶
Mentor's Note: In a hospital, doctors need patient data instantly. A slow or buggy system can be dangerous. This lab shows you how to build a safe, reliable lookup tool! π‘
π The Scenario: The Doctor's Search π©Ί¶
Imagine you are a doctor at a clinic in Surat.
- The Logic: A patient arrives and gives you their Patient ID. π¦
- The Search: You enter the ID into the system. It looks in the Patient Master table. π
- The Result:
- Found: The system displays their Name, DOB, and Phone. β
- Not Found: The system shows a friendly "Record not found" instead of crashing. πΈοΈ
π Concept Explanation¶
1. Using %TYPE π·οΈ¶
Instead of guessing if a name is VARCHAR2(50) or (100), we use Table.Column%TYPE. This makes the code "Smart" because it automatically copies the correct size from the table.
2. Error Trapping¶
We use the EXCEPTION block to catch NO_DATA_FOUND. This is the "Parachute" that ensures the program exits safely if an ID is wrong. πͺ
π¨ Visual Logic: The Lookup Flow¶
graph TD
A[Input ID π] --> B{Search in Table π}
B -- Found β
--> C[Display Full Record π€]
B -- Not Found β --> D[Trigger NO_DATA_FOUND πͺ]
D --> E[Show Error Message π¬]
C --> F[End π]
E --> F
π» Implementation: The Hospital Lab¶
-- π Scenario: Looking up a patient's medical file
-- π Action: Using SELECT INTO with exception handling
DECLARE
-- π¦ Smart variables using %TYPE
v_id Patientmaster.pat_id%TYPE;
v_name Patientmaster.pat_name%TYPE;
v_dob Patientmaster.DOB%TYPE;
v_phone Patientmaster.phoneno%TYPE;
BEGIN
-- π₯ 1. Accept ID from user
v_id := &Enter_Patient_ID;
-- π 2. Try to fetch details
SELECT pat_name, DOB, phoneno
INTO v_name, v_dob, v_phone
FROM Patientmaster
WHERE pat_id = v_id;
-- π€ 3. Show Result
DBMS_OUTPUT.PUT_LINE('--- Patient Profile ---');
DBMS_OUTPUT.PUT_LINE('Name: ' || v_name || ' π€');
DBMS_OUTPUT.PUT_LINE('DOB: ' || TO_CHAR(v_dob, 'DD-Mon-YYYY'));
DBMS_OUTPUT.PUT_LINE('Contact: ' || v_phone || ' π');
EXCEPTION
-- πΈοΈ 4. Safety Net
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('β οΈ Alert: Patient ID ' || v_id || ' does not exist.');
END;
/
π Sample Dry Run¶
Goal: Find ID 501 (Not in table)
| Step | Action | Status | Result |
|---|---|---|---|
| 1 | Input 501 | Variable set | Waiting... |
| 2 | Query | Search pat_id=501 |
No rows found! β |
| 3 | Jump | Go to EXCEPTION |
Handler reached πͺ |
| 4 | Show Alert | "ID 501 does not exist" |
π Complexity Analysis¶
- Time Complexity: \(O(1)\) - This is a Primary Key Search, which is the fastest way to find data in a database. β‘
π― Practice Problems¶
Easy Level π’¶
- Add a line to print the current system date (
SYSDATE) at the top of the report.
Medium Level π‘¶
- If the patient is found, also display their Doctor's Name by joining with the
Doctormastertable.
π‘ Interview Tip π¶
"Interviewers often ask: 'Can SELECT INTO return 0 rows?' Answer: No, if it returns 0 rows, it immediately stops and triggers the
NO_DATA_FOUNDexception. Your code must handle it!"