This question is in sequence of my previous Question required update same table on deletion a row.
I could write two solutions using Stored Procedure instead of trigger or nested-query .
Both use a helper function my_signal(msg).
A Stored Procedure to delete employee from Employee
Table.
- Fist Solution: use
UPDATE
rows in table, without join operation:
CREATE PROCEDURE delete_employee(IN dssn varchar(64)) BEGIN DECLARE empDesignation varchar(128); DECLARE empSsn varchar(64); DECLARE empMssn varchar(64); SELECT SSN, designation, MSSN INTO empSsn, empDesignation, empMssn FROM Employee WHERE SSN = dssn; IF (empSsn IS NOT NULL) THEN CASE WHEN empDesignation = 'OWNER' THEN CALL my_signal('Error: OWNER can not deleted!'); WHEN empDesignation = 'WORKER' THEN DELETE FROM Employee WHERE SSN = empSsn; WHEN empDesignation = 'BOSS' THEN BEGIN UPDATE Employee SET MSSN = empMssn WHERE MSSN = empSsn; DELETE FROM Employee WHERE SSN = empSsn; END; END CASE; ELSE CALL my_signal('Error: Not a valid row!'); END IF; END//
- Second solution: as I was suggested in my previous question using
INNER JOIN
CREATE PROCEDURE delete_employee(IN dssn varchar(64)) BEGIN DECLARE empDesignation varchar(128); DECLARE empSsn varchar(64); DECLARE empMssn varchar(64); SELECT SSN, designation, MSSN INTO empSsn, empDesignation, empMssn FROM Employee WHERE SSN = dssn; IF (empSsn IS NOT NULL) THEN IF (empDesignation = 'OWNER') THEN CALL my_signal('Error: OWNER can not deleted!'); END IF; UPDATE `Employee` A INNER JOIN `Employee` B ON A.SSN= B.MSSN SET B.MSSN = A.MSSN WHERE A.SSN = empSsn; DELETE FROM `Employee` WHERE SSN = empSsn; ELSE CALL my_signal('Error: Not a valid row!'); END IF; END//
I read here that using join is efficient for Efficient SELECT. But my problem includes only one table and I feel my solution(first) is much efficient than second because join will consume memory comparatively.
Please suggest me which is better and efficient, if Employee table
is sufficiently large. Which is better for me? Reason
EDIT: I checked for small table consist of 7 rows only, and both solution take same time.
mysql> CALL delete_employee(4);
Query OK, 1 row affected (0.09 sec)
I know SQL function behaves non-deterministically because table heuristics. Which choice is better? Either if you have some idea How query can be further optimised.