How do I get CURRENT_DATE in MSSQL?

坚强是说给别人听的谎言 提交于 2021-02-05 11:12:42

问题


I am using jpa 3.o with Hibernate. I have one named query:

SELECT COUNT(wt.id) FROM WPSTransaction wt WHERE wt.createdDate>= CURRENT_DATE

WPSTransaction is my entity class and createdDate is one of the columns in my class.

It's working fine in the Mysql Database. However, I'm moving to SQL Server 2012 and SQL server doesn't seem to compile the CURRENT_DATE value. I've tried GETNOW() and NOW() methods as well as current_date() method and CURRENT_TIMESTAMP without any luck.


回答1:


MS SQL Server fails to conform to the standard here - it does not provide a current_date keyword.

You must instead use the SQL-server specific GETDATE() function, as the document linked shows.

Because current_date is a keyword in the spec, you can't just create a user-defined current_date() function in MS SQL and expect it to work the same. So unfortunately you're stuck with database-specific code here.




回答2:


The function to return the current date in MS SQL is GETDATE(), so your query should read

SELECT COUNT(wt.id) FROM WPSTransaction wt WHERE wt.createdDate >= GETDATE()



回答3:


How about:

Query q = entityManager.createQuery("SELECT COUNT(wt.id) FROM WPSTransaction wt WHERE wt.createdDate>= :d");
q.setParam("d", new Date());

No database specific code needed.



来源:https://stackoverflow.com/questions/13884830/how-do-i-get-current-date-in-mssql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!