简体   繁体   中英

SQL Server DATEPART() function

Today I wrote two queries on Datepart() and get different returns below

Query #1:

Select Datepart(day,'2015-07-05')

returns '5', which I expected.

Query #2:

Select Datepart(day, 2015-07-05)

Returns '27', which is a little bit funny, and I don't understand how 27 is being returned.

The difference between these two queries is one with the date inside ' ', and the other without.

Anybody can help me out here?

2015-07-05 is just a mathematical expression which adds up to the integer 2003. (Subtracting 7 from 2015 gives 2008 then subtract 5)

2003 evaluates to '1905-06-27' when implicitly cast to datetime as casting int to datetime works the same as adding that number of days to the base date of 1 Jan 1900 (ie equals DATEADD(DAY, 2003,'19000101') ).

So this is where the 27 comes from.

The correct way to denote date literals in SQL Server is as a string '2015-07-05' (ISO format - unambiguous for newer datetime datetypes) or '20150705' (unambiguous for legacy datatypes) or using the ODBC format { d '2015-07-05' } .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM