Home > Database > Mysql Tutorial > body text

How to Create a MySQL Trigger to Update a Different Table\'s Column After an Insert?

Patricia Arquette
Release: 2024-11-24 04:12:11
Original
241 people have browsed it

How to Create a MySQL Trigger to Update a Different Table's Column After an Insert?

MySQL Trigger to Update Different Table's Column after Insert

This question involves creating a MySQL trigger that updates the status column in the BookingRequest table based on the insertion of a row into the OccupiedRoom table.

The initial trigger code attempted to directly update the BookingRequest table using a comparison between BookingRequest.idRequest and NEW.idRequest. However, this approach was unsuccessful.

To resolve this issue and create a functional trigger, the code below should be used:

DELIMITER $$
CREATE TRIGGER occupy_trig
AFTER INSERT ON `OccupiedRoom` FOR EACH ROW
begin
       DECLARE id_exists Boolean;
       -- Check BookingRequest table
       SELECT 1
       INTO @id_exists
       FROM BookingRequest
       WHERE BookingRequest.idRequest= NEW.idRequest;

       IF @id_exists = 1
       THEN
           UPDATE BookingRequest
           SET status = '1'
           WHERE idRequest = NEW.idRequest;
        END IF;
END;
$$
DELIMITER ;
Copy after login

This trigger utilizes a variable @id_exists to check if the idRequest from the OccupiedRoom table exists in the BookingRequest table. If it does, it sets the status column in the BookingRequest table to '1'.

By using the placeholder NEW within the trigger, the comparison is now performed correctly between the inserted row's idRequest and the corresponding idRequest in the BookingRequest table.

The above is the detailed content of How to Create a MySQL Trigger to Update a Different Table\'s Column After an Insert?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template