Adding dates in SQL Server using the add operator

Hi

In SQL Server we can add day to date in two ways. We can use the DATEADD function to add date like

SELECT DATEADD(dd, 2, GETDATE())

This adds one day to the current date. We can also use the following query to get the current date and add a one-day to it. Both the queries will give same results.

SELECT GETDATE() + 2

If you are thinking that why does an + operator produces exactly same results? Read on.

As we know that the datetime data occupies 8 bytes (4 of them stores number of days after or before January 01 1900 and the other 4v store number of 3.33 ms clock tics since midnight. All the number are stored as integer data type.

So when we run the query SELECT GETDATE() + 2 we are actually adding datetime data to an integer data. Since the datetime data type has higher precedence, the integer number 1 has to be implicitly converted to a data type of the addend with higher precedence.

When we run the SELECT GETDATE() + 1, we are adding two datetime values. And as we know that internally datetime values are interpreted as integers. As a result an addition operation that uses a plus sign (+) becomes perfectly valid.

Note that the addition operator in date time calculation requires at least one datetime addend, which again has to be addend with the highest precedence.

Thanks
Vikram


Share this post   Email it |  digg it! |  reddit! |  bookmark it!

Feedback

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 
Copyright © 2006 - 2009 Vikram Lakhotia