简体   繁体   中英

Can I constraint an AutoIncremented column not to accept values from outside?

I have an AutoIncremented column (ID), and I want to have a constraint that only the database ever fills in this column. Is there a constraint for that?

I don't think there's a declarative constraint that can do this.

You can do it using a trigger, for example:

DELIMITER //

CREATE TRIGGER ForceId BEFORE INSERT ON MyTable
FOR EACH ROW
BEGIN
  SET NEW.id = DEFAULT;
END //

DELIMITER ;

I just tested this on MySQL 5.1.41 and it seems to work. If I specify a value for id in my INSERT statement, it ignores my value and generates a new surrogate key value.

INSERT INTO MyTable (id, name) VALUES (DEFAULT, 'Bill');
INSERT INTO MyTable (id, name) VALUES (123, 'John');
SELECT * FROM MyTable;
+----+-------+
| id | name  |
+----+-------+
|  1 | bill  |
|  2 | john  |
+----+-------+

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