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?
views:
37answers:
1
+1
A:
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 |
+----+-------+
Bill Karwin
2009-12-19 18:08:46