Quantcast
Channel: CodeSection,代码区,SQL Server(mssql)数据库 技术分享 - CodeSec
Viewing all articles
Browse latest Browse all 3160

Using DATEADD, DATEDIFF and DATEPART T-SQL Functions in Simple Terms

$
0
0

Using DATEADD, DATEDIFF and DATEPART T-SQL Functions in Simple Terms

This article focuses on developing a basic understanding of how to use one of the most common Transact-SQL date functions: DATEADD, DATEDIFF, and DATEPART.

In this article, I also stressed the importance of properly using these date functions in daily date manipulations followed by some interesting scenarios in which these date functions can be used in a collaborative way to solve slightly complex date calculations.

Since these functions are primarily used in date manipulations, let us first try to understand what we mean by date manipulation.

Understanding Date Manipulation

The date-time values often need to be modified as per requirement, and the method of modifying or handling or controlling the date-time calculations is known as date manipulation.

We also refer to this situation (date manipulation) when a date value is read from a database and then modified before it gets stored again.

Customer-Order Scenario

An interesting example of date manipulation is a customer-order scenario, when an order placed by a customer is processed, the delivery date must be set 5 days ahead of the order date , so this means that a developer must use T-SQL date function(s) to manipulate (modify) the order date to calculate the delivery date .

Sample Daily Sales Report

A slightly complex example is when a business user runs a Daily Sales Report if it shows yesterday’s results.

For instance, if we run the Daily Sales Report on Sunday at 11:00, it will show us results based on Saturday, and if we run it on Saturday at 17:00, it will show us all the results on Friday, because the current day is not over yet and the most recent complete day available is yesterday. This is how most professional daily reports including financial reports are designed to run.

In this example, the current date is manipulated (modified) to get the previous date, which contains sales records for a complete day.


Using DATEADD, DATEDIFF and DATEPART T-SQL Functions in Simple Terms
Implementing the Examples

Please keep the above examples in mind since we are going to implement these scenarios once we get a good understanding of using some of the most common date functions described in this article.

Understanding Date Functions

Let’s first look at some basic date functions that can help us meet date manipulation requirements, such as determining days between two dates (order date and delivery date), getting last week’s sales records based on current date or calculating the expected expiry date based on the production date and so on.

Since there are no hard and fast rules, we begin exploring DATEPART function first.

Using DATEPART Function Simple Definition

DATEPART function is used to return a part of a given date in a numeric value.

The part can be the day of the date, month of the date, year of the date etc.

For example, we can use the DATEPART function to get the day of a given date to determine whether an order was placed on Sunday or not.

Another example is to get the month of a given date to be passed on to another date function for further processing.

Microsoft Definition

This function returns an integer representing the specified datepart of the specified date .

Compatibility

According to Microsoft documentation, this function is compatible with the following SQL Server versions:

SQL Server 2008 plus Azure SQL Database Azure SQL Data Warehouse Parallel Data Warehouse Syntax DATEPART (datepart , date) Example 1: Getting Year Part of the Date

Let us also define a certain date ( OrderDate ) to get its desired part (Day, Month, Year) using the DATEPART function.

To get Year of the order date, we simply pass YEAR followed by Order Date (@OrderDate) in the DATEPART function as follows:

-- Define Order Date DECLARE @OrderDate DATETIME2='2017-01-11' -- Getting Year of the Order Date SELECT DATEPART(YEAR,@OrderDate) as Year_OrderDate
Using DATEADD, DATEDIFF and DATEPART T-SQL Functions in Simple Terms
Example 2: Getting Month Part

If we are interested to know the month of the date then Month needs to be passed into the DATEPART function as follows:

-- Define Order Date DECLARE @OrderDate DATETIME2='2017-01-11' -- Getting Month of the Order Date SELECT DATEPART(MONTH,@OrderDate) as Month_OrderDate
Using DATEADD, DATEDIFF and DATEPART T-SQL Functions in Simple Terms
Example 3: Getting Day Part

To find the Day part of the date, simply pass DAY into the DATEPART function as follows:

-- Define Order Date DECLARE @OrderDate DATETIME2='2017-01-11' -- Getting Day of the Order Date SELECT DATEPART(DAY,@OrderDate) as Day_OrderDate
Using DATEADD, DATEDIFF and DATEPART T-SQL Functions in Simple Terms
Example 4: Getting Week Day Part

To get the Week Day part of the date, simply pass WEEKDAY into the DATEPART function as follows:

-- Define Order Date DECLARE @OrderDate DATETIME2='2017-01-11' -- Getting Week Day of the Order Date SELECT DATEPART(WEEKDAY,@OrderDate) as WeekDay_OrderDate

We are getting 4, which is Wednesday starting from Sunday, which is 1.

Similarly, we can also get a Quarter, Hour, Minute, Second part of the date.

Let’s move on to the next date function.

Using DATEADD Function Simple Definition

The DATEADD function is used to add or subtract a date.

For example, we can find out what the date will be after four days or four days before.

This is very handy in the scenarios where the expected date has to be calculated based on a given date such as membership expiry date must be exactly one year from the registration date.

Another example is to calculate the course end date which must be exactly two months after the course start date.

Microsoft Definition

This function adds a specified number value (as a signed integer) to a specified datepart of an input date value, and then returns that modified value.

Compatibility

According to Microsoft documentation, this function is compatible with the following SQL Server versions:

SQL Server 2008 plus Azure SQL Database Azure SQL Data Warehouse Parallel Data Warehouse Syntax DATEADD (datepart, number, date)

Datepart is any part of the date such as day, month, year, weekday, hour etc.

Number is then number of the datepart (day, month, year etc.) to be added or subtracted

Date is a given date which needs to be added or subtracted using the DATEADD function

Example 1: Getting Next Year Date

Let us also define a certain date (Registration Date) which is going to be added or subtracted using the DATEADD function based on the requirements.

The next year date can be obtained by adding 1 to the Year datepart.

To get the next year from the registration date, we simply add DatePart Year followed by 1 followed by Registration Date (@RegistrationDate) in the DATEADD function

Viewing all articles
Browse latest Browse all 3160

Trending Articles