Advertisement
vvccs

ADS_5_Trigger_cursor

Oct 15th, 2024 (edited)
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MySQL 1.76 KB | None | 0 0
  1. MYSQL
  2.  
  3. CREATE TABLE employee (
  4.  emp_id INTEGER PRIMARY KEY,
  5.  emp_name VARCHAR(20),
  6.  salary DECIMAL
  7. );  
  8. INSERT INTO employee VALUES (1, 'John', 40000);
  9. INSERT INTO employee VALUES (2, 'Doe', 50000);
  10. CREATE TABLE salary_history (
  11.  emp_id INTEGER,
  12.  old_salary DECIMAL
  13. );
  14. DELIMITER //
  15. CREATE TRIGGER before_salary_update
  16. BEFORE UPDATE ON employee
  17. FOR EACH ROW
  18. BEGIN
  19.   INSERT INTO salary_history (emp_id, old_salary) VALUES (OLD.emp_id, OLD.salary);
  20. END//
  21. DELIMITER ;
  22. drop trigger before_salary_update;
  23.  
  24. UPDATE employee SET salary = salary + 10000 WHERE emp_id = 1;
  25. UPDATE employee SET salary = salary + 5000 WHERE emp_id = 2;
  26. SELECT * FROM employee;
  27. SELECT * FROM salary_history;
  28.  
  29. --CURSOR
  30.  
  31. CREATE TABLE employee_backup (
  32.  emp_id INT,
  33.  emp_name VARCHAR(20),
  34.  salary DECIMAL
  35. );
  36.  
  37. DELIMITER //
  38. CREATE PROCEDURE backup_employee()
  39. BEGIN
  40.    DECLARE done INT DEFAULT FALSE;
  41.    DECLARE v_emp_id INT;
  42.    DECLARE v_emp_name VARCHAR(20);
  43.    DECLARE v_salary DECIMAL;
  44.    -- Declare cursor
  45.    DECLARE emp_cursor CURSOR FOR
  46.    SELECT emp_id, emp_name, salary FROM employee;
  47.    -- Declare exit handler
  48.    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
  49.    -- Open cursor
  50.    OPEN emp_cursor;
  51.    -- Fetch and insert rows
  52.    read_loop: LOOP
  53.       FETCH emp_cursor INTO v_emp_id, v_emp_name, v_salary;
  54.       IF done = 1 THEN
  55.          LEAVE read_loop;
  56.       END IF;
  57.  
  58.       -- Insert the fetched data into the backup table
  59.       INSERT INTO employee_backup (emp_id, emp_name, salary)
  60.       VALUES (v_emp_id, v_emp_name, v_salary);
  61.    END LOOP;
  62.    -- Close cursor
  63.    CLOSE emp_cursor;
  64. END //
  65. DELIMITER ;
  66.  
  67. drop procedure backup_employee;
  68.  
  69. -- Call the stored procedure
  70. CALL backup_employee();
  71. SELECT * FROM employee_backup;
  72. DROP TABLE employee_backup;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement