开发者

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

开发者 https://www.devze.com 2022-12-14 22:29 出处:网络
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 declara

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  |
+----+-------+
0

精彩评论

暂无评论...
验证码 换一张
取 消