SQL Date Processing and conversion

Source: Internet
Author: User

DECLARE @dt datetime set @dt =getdate () DECLARE @number int Set @number = 3--1. Specifies the date--a the first or last day of the year. The first day of the year select CONVERT (char (5), @dt, +) + ' 1-1 '--b. The last day of the year select CONVERT (char (5), @dt, 120) + ' 12-31 '--2. --a the first or last day of the quarter on which the specified date is located.  First day of the quarter select CONVERT (datetime, CONVERT (char (8), DATEADD (Month, DATEPART (Quarter, @dt) *3-month (@dt)-2, @dt), 120) + ' 1 ') --b. Last day of the quarter (case judgment) SELECT CONVERT (datetime, CONVERT (char (8), DATEADD (Month, DATEPART (Quarter, @dt) *3-month (@dt), @ DT), +case when DATEPART (Quarter, @dt) in (1,4) and then ' ELSE ', ' End '--c. The last day of the quarter (direct extrapolation method) SELECT DATEADD (Day,-1, CONVERT (char (8), DATEADD (Month, 1+datepart (Quarter, @dt) *3-month (@dt), @dt), 120) + ' 1 ')--3. --a the first or last day of the month in which the specified date is located. First day of the month Select CONVERT (Datetime,convert (char (8), @dt, +) + ' 1 ')--b. The last day of the month Select DATEADD (Day,-1,convert (char (8), DATEADD (month,1, @dt), (+) + ' 1 ')--c. The last day of the month (easy-to-use error method) SELECT DATEADD (Month,1,dateadd (Day,-day (@dt), @dt))--4. Select DATEADD (Day, @number-datepart (Weekday, @dt), @dt)--5 at any time of the week on which the specified date is located. The specified dateA few--a on any week of the week.  Sunday is the day of the week select DATEADD (Days, @number-(DATEPART (Weekday, @dt) [email protected] @DATEFIRST-1)%7, @dt)--b.  Monday Days of the week select DATEADD (Day, @number-(DATEPART (Weekday, @dt) [email protected] @DATEFIRST-2)%7-1, @dt)

SQL Date Processing and conversion

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.