How to create trigger for broken cars using IF statement

后端 未结 1 1289
终归单人心
终归单人心 2021-01-28 14:21

I want to create a trigger that will not allow to rent a car if it is currently being repaired. Im quite new in triggers... could anyone shed some light on this aspect of trigge

1条回答
  •  走了就别回头了
    2021-01-28 14:39

    I didn't tested it so it might have a missing condition or something like that. But it should help you on the correct path

    Query

    DELIMITER $$
    CREATE TRIGGER `check_repair` BEFORE INSERT ON `bookings` FOR EACH ROW BEGIN 
        # We need to save the "count"
        DECLARE inspections_count INT DEFAULT 0;
    
        # Check if where is a repair going which matches the vehicle_id
        SELECT
          1 INTO inspections_count # store the "count" into the variable.
        FROM inspections
        WHERE
            inspections.vehicle_id = NEW.vehicle_id
          AND
            repair_complete = 'No'
        ORDER BY 
         inspections.start_date DESC
       LIMIT 1;
    
        # if there is a "count" stop the insert.
        IF inspections_count = 0 THEN 
          SIGNAL SQLSTATE '45000'
          SET MESSAGE_TEXT = 'vehicle is in repair';
        END IF;
    END
    $$
    DELIMITER ;
    

    0 讨论(0)
提交回复
热议问题