2017-08-16 157 views
1

我在創建使用CURRENT_TIMESTAMP指定日期的表時遇到了一些問題。我需要這個,因爲我使用java jpa實體來按日期檢索它們。如果我運行到本地h2數據庫,我沒有問題。SQL命令中的TIMESTAMP和CURRENT_TIMESTAMP問題

在這個例子中:

INSERT INTO Post (id, title, slug, teaser, body, author_id, posted_on) 
VALUES (1, 'Spring Boot Rocks!', 'spring-boot-rocks', @TEASER, @BODY, 1, CURRENT_TIMESTAMP); 

一切都被創建和完美的作品,但是當我嘗試在我連接了Azure的SQL數據庫一樣查詢到我的錯誤

Failed to execute query. Error: Cannot insert an explicit value into a timestamp column. Use INSERT with a column list to exclude the timestamp column, or insert a DEFAULT into the timestamp column.

如果我嘗試將CURRENT_TIMESTAMP更改爲TIMESTAMP,我會得到;

Failed to execute query. Error: Invalid column name 'TIMESTAMP'. If I change it to DEFAULT as the previous error suggests the tables get created but I can't retrieve them by date of creation since DEFAULT is not a time value.

完整的查詢

SET IDENTITY_INSERT author ON 

insert into author(id,first_name,last_name,email) values (1,'Dan','Vega','[email protected]'); 
insert into author(id,first_name,last_name,email) values (2,'John','Smith','[email protected]'); 

SET IDENTITY_INSERT author OFF 
SET IDENTITY_INSERT post ON 

DECLARE @TEASER varchar(4000) = 'text...' 
DECLARE @BODY varchar(4000) = 'text...' 

insert into Post(id,title,slug,teaser,body,author_id,posted_on) values (1,'Spring Boot Rocks!','spring-boot-rocks',@TEASER,@BODY,1,CURRENT_TIMESTAMP); 
insert into Post(id,title,slug,teaser,body,author_id,posted_on) values (2,'Spring Data Rocks!','spring-data-rocks',@TEASER,@BODY,1,CURRENT_TIMESTAMP); 
insert into Post(id,title,slug,teaser,body,author_id,posted_on) values (3,'John Blog Post 1','john-blog-post-1',@TEASER,@BODY,2,CURRENT_TIMESTAMP); 
insert into Post(id,title,slug,teaser,body,author_id,posted_on) values (4,'John Blog Post 2','john-blog-post-2',@TEASER,@BODY,2,CURRENT_TIMESTAMP); 
insert into Post(id,title,slug,teaser,body,author_id,posted_on) values (5,'John Blog Post 3','john-blog-post-3',@TEASER,@BODY,2,CURRENT_TIMESTAMP); 
insert into Post(id,title,slug,teaser,body,author_id,posted_on) values (6,'Refactoring our Spring Data Project','refactoring-spring-data-project',@TEASER,@BODY,1,CURRENT_TIMESTAMP); 

SET IDENTITY_INSERT post OFF 

回答

4

在SQL Server(及SQL Azure)的TIMESTAMP數據類型是什麼ISO/ANSI標準定義(這是SQL原來的Sybase遺產的剩服務器)。

這真的只是樂觀併發檢查的二進制計數器 - 它有NOTHING做一個日期和/或時間了!

要儲存和處理日期和時間,使用的數據類型DATE(只是日期 - 沒時間),或DATETIME2(n)日期&時間,而不是

+1

如果我取代'和'DATE'我有CURRENT_TIMESTAMP' '無法執行查詢。錯誤:無效的列名'DATE'。' – MrSir

+0

@MrSir:您不必用任何東西來替換'CURRENT_TIMESTAMP' - 您需要**更改**表中'posting_on'列的數據類型** ** (從'TIMESTAMP'到例如'DATETIME2(0)')你將數據插入! –

+0

我試圖改變它與查詢'ALTER TABLE後 ALTER COLUMN posted_on DATETIME2(0); '我有'不能更改列'posted_on',因爲它是時間戳。' – MrSir

0

通過重新使用application.properties spring.jpa.hibernate.ddl-auto=create-drop數據庫和更換

固定
@CreatedDate @Column(columnDefinition = "TIMESTAMP") 
private Date postedOn; 

@CreatedDate @Column(columnDefinition = "DATETIME2(0)") 
private Date postedOn;