2010-04-10 128 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); 
相關問題