It looks like i cant add a not null constraint or remove a default constraint. I would like to add a datetime column to a table and have all the values set to anything (perhaps 1970 or year 2000) but it seems like i cant use not null without a default and i cant remove a default once added in. So how can i add this column? (once again just a plain datetime not null)
而不是使用ALTER TABLE ADD COLUMN
,创建一个具有额外列的新表,并复制旧数据.这将使您免受限制,ALTER TABLE
并让您有一个NOT NULL
没有默认值的约束.
ALTER TABLE YourTable RENAME TO OldTable; CREATE TABLE YourTable (/* old cols */, NewColumn DATETIME NOT NULL); INSERT INTO YourTable SELECT *, '2000-01-01 00:00:00' FROM OldTable; DROP TABLE OldTable;
编辑:ALTER TABLE的官方SQLite文档现在警告上述过程,因为它"可能会破坏对触发器,视图和外键约束中对该表的引用."安全的替代方法是为新表使用临时名称,如这个:
CREATE TABLE NewTable (/* old cols */, NewColumn DATETIME NOT NULL); INSERT INTO NewTable SELECT *, '2000-01-01 00:00:00' FROM YourTable; DROP TABLE YourTable; ALTER TABLE NewTable RENAME TO YourTable;