当前位置:  开发笔记 > 数据库 > 正文

Add not null DateTime column to SQLite without default value?

如何解决《AddnotnullDateTimecolumntoSQLitewithoutdefaultvalue?》经验,为你挑选了1个好方法。

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)



1> dan04..:

而不是使用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;

推荐阅读
TXCWB_523
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有