简体   繁体   中英

MySQL Insert/Update Trigger with AUTO_INCREMENT

So, I've got a table roughly as follows:

CREATE TABLE CUSTOMER (
    CUSTID              INT NOT NULL AUTO_INCREMENT,
    NAME                CHAR (45),
    CONSTRAINT CUSTOMER_PRIMARY_KEY PRIMARY KEY (CUSTID))
AUTO_INCREMENT = 100;

I'm auto incrementing the CUSTID so that it's possible to simply insert a name and have it created with the next available CUSTID . However, I also want to ensure that it isn't possible to set the CUSTID value to zero, either on creation of the row or on update so I've constructed the following trigger:

DELIMITER $$
CREATE TRIGGER `custid_before_insert` BEFORE INSERT ON `CUSTOMER`
FOR EACH ROW
BEGIN
    IF (NEW.CUSTID) <= 0 THEN
        SIGNAL SQLSTATE '12345'
            SET MESSAGE_TEXT = 'Check constraint on CUSTOMER.CUSTID failed';
    END IF;
END$$

CREATE TRIGGER `custid_before_update` BEFORE UPDATE ON `CUSTOMER`
FOR EACH ROW
BEGIN
    IF (NEW.CUSTID) <= 0 THEN
        SIGNAL SQLSTATE '12345'
            SET MESSAGE_TEXT = 'Check constraint on CUSTOMER.CUSTID failed';
    END IF;
END$$
DELIMITER ;

Unfortunately in my blissful ignorance of how AUTO_INCREMENT worked, I've come to the conclusion that this is the wrong way to go about this. Trying to insert a customer with no CUSTID value is tripping the trigger causing the insert to fail which I presume is due to the value being a zero before insertion when AUTO_INCREMENT assigns it a value.

Would the best way to do this really be to change the trigger to occur after the insert and delete the row or is there a better way to do this to just throw an error?

The insert trigger is not needed.

From Auto_Increment

No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign 0 to the column to generate sequence numbers.

EG

create table t(id int auto_increment, primary key(id));
insert into t(id) values (0);
select id from t;
# 1

Update:

To allow the insert to complete when CUSTID is not specified,

INSERT INTO customer(name) VALUES('Chuck');

check for null in the trigger:

IF NEW.CUSTID IS NOT NULL AND NEW.CUSTID <= 0 THEN

Inserting '0' into an auto-increment column causes it to increment the same as inserting NULL, so you really neither need nor want the INSERT trigger. Try it with just the UPDATE trigger.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM