问题
Those are the tables:
CREATE TABLE Staff
(
staffID INTEGER,
staffName VARCHAR(20),
staffSurname VARCHAR(20),
DOB DATE NOT NULL,
staffBranchNo INTEGER,
salary DECIMAL(5,2),
startDateOfWork DATE
);
ALTER TABLE Staff
ADD (CONSTRAINT staff_pk PRIMARY KEY(staffID));
CREATE TABLE Branch
(
branchNo INTEGER,
branchCity varchar(20),
branchTotalStaffNumber INTEGER
);
ALTER TABLE Branch
ADD (CONSTRAINT branch_pk PRIMARY KEY(branchNo));
I need a trigger that updates branchTotalStaffNumber according to staffBranchNo, when a new staff member is added, an existing staff member is updated or deleted.
I tried a few triggers but none of them included three of those operations as I need. The trigger below is not working.
CREATE OR REPLACE TRIGGER staff_trigger
BEFORE INSERT OR UPDATE OR DELETE ON Staff
FOR EACH ROW
BEGIN
CASE
WHEN INSERTING THEN
INSERT INTO branch (branchTotalStaffNumber)
VALUES(:NEW.branchTotalStaffNumber);
WHEN UPDATING THEN
UPDATE branch SET branchTotalStaffNumber = :NEW.branchTotalStaffNumber;
WHEN DELETING THEN
delete from branch where staffBranchNo = :new.branchTotalStaffNumber;
END CASE;
END;
/
回答1:
You should not use trigger
for storing the calculated values. But if you are learning then you shoild use the following code (see inline comments)
CREATE OR REPLACE TRIGGER staff_trigger
BEFORE INSERT OR UPDATE OR DELETE ON Staff
FOR EACH ROW
BEGIN
IF INSERTING THEN -- used IF . CASE usage is not allowed as IF
UPDATE branch SET branchTotalStaffNumber = branchTotalStaffNumber + 1
Where branchno = :new.staffBranchNo; -- used :new to identify the record
ELSIF UPDATING THEN
-- update the branch table only if staffBranchno is updated
-- adding one staff to the new branch
IF :new.staffBranchNo <> :old.staffBranchNo THEN
UPDATE branch SET branchTotalStaffNumber = branchTotalStaffNumber + 1
Where branchno = :new.staffBranchNo;
-- removing one staff from old branch
UPDATE branch SET branchTotalStaffNumber = branchTotalStaffNumber - 1
Where branchno = :old.staffBranchNo;
END IF;
ELSE -- IF DELETING can be omitted
-- removing one staff from branch for delete action
UPDATE branch SET branchTotalStaffNumber = branchTotalStaffNumber - 1
Where branchno = :old.staffBranchNo;
END IF;
END;
/
Please note that you can also create the trigger using OF
clause and column name in it. It will execute the trigger only if value of the mentioned column on OF
clause is changed.
来源:https://stackoverflow.com/questions/65187312/is-there-any-way-to-create-this-trigger-or-should-i-use-something-else