如何在sqlite3中创建具有默认值的日期时间列? [英] How to create a datetime column with default value in sqlite3?
问题描述
有没有办法在 sqlite3 中创建一个表,该表的日期时间列默认为现在"?
Is there a way to create a table in sqlite3 that has a datetime column that defaults to 'now'?
以下语句返回语法错误:
The following statement returns a syntax error:
create table tbl1(id int primary key, dt datetime default datetime('now'));
更新:以下是 Sky Sanders 提供的正确 ddl:
Update: Here's the correct ddl courtesy of Sky Sanders:
create table tbl1(id int primary key, dt datetime default current_timestamp);
推荐答案
试试这个:
create table tbl1(id int primary key, dt datetime default current_timestamp);
背景:
DEFAULT 约束指定了一个执行操作时使用的默认值插入.该值可能是 NULL,一个字符串常量、数字或包含在其中的常量表达式括号.默认值可能也是特别的之一大小写无关的关键字CURRENT_TIME、CURRENT_DATE 或CURRENT_TIMESTAMP.如果值为NULL,字符串常量或数字,它每当插入到列中不包含的 INSERT 语句为列指定一个值是执行.如果值为CURRENT_TIME、CURRENT_DATE 或CURRENT_TIMESTAMP,则当前UTC 日期和/或时间被插入到列.对于 CURRENT_TIME,格式为 HH:MM:SS.对于 CURRENT_DATE,YYYY-MM-DD.格式为CURRENT_TIMESTAMP 是YYYY-MM-DD时:分:秒".
The DEFAULT constraint specifies a default value to use when doing an INSERT. The value may be NULL, a string constant, a number, or a constant expression enclosed in parentheses. The default value may also be one of the special case-independant keywords CURRENT_TIME, CURRENT_DATE or CURRENT_TIMESTAMP. If the value is NULL, a string constant or number, it is inserted into the column whenever an INSERT statement that does not specify a value for the column is executed. If the value is CURRENT_TIME, CURRENT_DATE or CURRENT_TIMESTAMP, then the current UTC date and/or time is inserted into the columns. For CURRENT_TIME, the format is HH:MM:SS. For CURRENT_DATE, YYYY-MM-DD. The format for CURRENT_TIMESTAMP is "YYYY-MM-DD HH:MM:SS".
来自http://www.sqlite.org/lang_createtable.html
这篇关于如何在sqlite3中创建具有默认值的日期时间列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!