2010-04-10 122 views
40

有没有办法在sqlite3中创建一个datetime列默认为'now'的表?我可以在sqlite3中使用默认值创建日期时间列吗?

下面的语句返回一个语法错误:

create table tbl1(id int primary key, dt datetime default datetime('now')); 

更新:这里是Sky Sanders正确的DDL礼遇:

create table tbl1(id int primary key, dt datetime default current_timestamp); 
+0

@NobodyMan - 也许你可以更新你的问题,包括适用于其他人会很容易找到DDL。 – 2010-04-11 00:31:48

+0

@天空 - 我不反对,但不是让你的答案是多余的?另外,如果我做了编辑,我应该更换不正确的代码片段,或者直接附加正确答案的问题?我对SO礼仪有点无知:-) – NobodyMan 2010-04-14 17:10:01

+1

当你用一个最终为你工作的例子添加你的问题的更新时,它并没有真正减少答案。很多答案都可以提供有用的建议,因为我的ddl片段和背景可以帮助您修复ddl。通过添加正确的语句来确认解决方案是增值。在任何情况下都不会更改原始代码,这就是具有相同问题的人如何找到此解决方案。无论如何,这是一个有争议的问题,我编辑了我的答案,提出了你的ddl的工作版本。欢呼 – 2010-04-14 18:51:49

回答

67

试试这个:

create table tbl1(id int primary key, dt datetime default current_timestamp); 

背景:

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

+6

请注意,如果你想毫秒使用'default(STRFTIME('%Y-%m-%d%H:%M:%f','NOW'))','current_timestamp'精确到秒。 – TWiStErRob 2015-03-07 23:05:01

11
... default (datetime(current_timestamp)) 

以下default表达式必须是在括号中。如果您想使用SQLite date and time functions or modifiers执行日期算术,此表单非常有用。

+0

Doug,parenth只有在涉及表达式时才需要。 'current_xxxx'是关键字,充当文字值。 http://www.sqlite.org/syntaxdiagrams.html#column-constraint – 2010-04-11 00:23:52

+0

天空,是的,是不是我说的?我的观点是,如果你想要的不仅仅是关键字提供的内容,你可以使用表达式,但表达式必须在括号内;原始问题中的创建语句缺少括号。 – 2010-04-11 22:10:50

+1

没有理由写datetime(current_timestamp)。只需使用current_timestamp即可。 – dan04 2010-04-12 05:38:12

6

CURRENT_TIMESTAMP是一个文字值就像'mystring'

列约束:

enter image description here

字面值:

enter image description here

+0

是的,'datetime('now')'OP使用的是'expr',所以它需要括号。 – TWiStErRob 2015-04-29 13:51:27

-1

你可以用下面的查询为表使用当前日期值

create table tablename (date_field_name Created_on default CURRENT_DATE); 
相关问题