SQL returns the date of today or tomorrow

Source: Internet
Author: User
Tags datetime getdate

Let's take a look at common date functions.

Date functions:

1. Last month: for example, the last month is 201201 :( CONVERT ([varchar] (6), dateadd (month, (-1), getdate (), (112 )))
2, yesterday: 2012-02-02 CONVERT (varchar (100), GETDATE ()-1, 23)
3. Today: 2012-02-03 CONVERT (varchar (100), GETDATE (), 23)
4, last day of last month: 23:59:59. 997 dateadd (MS,-3, DATEADD (mm, DATEDIFF (mm, 0, getdate (), 0 ))
5. On the first day of the month, 00:00:00. 000 DATEADD (mm, DATEDIFF (mm, 0, getdate (), 0)


Next let's look at the T-SQL user-defined function to return the day before or after the date

The code is as follows: Copy code
-- ===================================================== ======
-- Author: Insus. NET
-- Create date: 2012-03-22
-- Description: specifies the date, and returns the date of the previous day.
-- ===================================================== ======
Create function [dbo]. [udf_Yesterday] (@ datetime DATETIME)
RETURNS DATETIME
AS
BEGIN
Return dateadd (DAY,-1, @ datetime)
END
GO

Return the next day:

 

The code is as follows: Copy code

-- ===================================================== ======
-- Author: Insus. NET
-- Create date: 2012-03-22
-- Description: specifies the date, and returns the date of the next day.
-- ===================================================== ======
Create function [dbo]. [udf_Tomorrow] (@ datetime DATETIME)
RETURNS DATETIME
AS
BEGIN
Return dateadd (DAY, 1, @ datetime)
END
GO

Instance

The code is as follows: Copy code

SELECT [dbo]. [udf_Yesterday] (CURRENT_TIMESTAMP) AS [Yesterday]
SELECT [dbo]. [udf_Tomorrow] (CURRENT_TIMESTAMP) AS [Tomorrow]

Effect

Note: For better specification and code maintenance, Insus. NET often refactor some reusable code into a function.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.