Welcome to MSDN Blogs Sign in | Join | Help

Aakash Kambuj's blog

Windows Live Core
datetime quirks

Datetime and smalldatetime data types can be confusing at times.
For example, consider the following select statement:

create table t1(c1 datetime)
go
insert t1 values('20010101')
go

select c1 + '1/1/3' from t1
go

 If you expected '1/1/3' to represent january 1, 3AD, you're in for a little surprise.
This addition of a string to a datetime produces the following result:

2104-01-02 00:00:00.000

This happens because SQL Server treats '1/1/3' as '1/1/2003'. Then it calculates the difference in days between '1/1/2003' and '1/1/1900', and adds the numbers of days to the value stored in c1. This happens because January 1, 1900 is treated as the base date in SQL Server 2000 and SQL Server 2005.

Posted: Tuesday, September 14, 2004 4:01 PM by aakashk

Comments

Suthep Sangvirotjanaphat said:

I think you missed FROM clause in the last statement.
so it should be:

SELECT c1 + '1/1/3' FROM t1


I am an instructor in Thailand.
At here, we have several developers that confused
about datetime datatype. So I like this blog
and add some more experiments as follows:

SELECT CAST(c1 AS decimal) FROM t1
SELECT CAST(CAST('1/1/3' AS datetime) AS decimal)
SELECT CAST(c1 + '1/1/3' AS decimal) FROM t1

results:
36890
37620
74510

# September 14, 2004 11:57 PM
Anonymous comments are disabled
Page view tracker