SQL Server learning record gets the first and last day of every quarter of each month

Source: Internet
Author: User
Tags getdate

DECLARE@dtdatetimeSET@dt=GETDATE()DECLARE@numberintSET@number=3--1. Specify a date the first or last day of the year--A. The first day of the yearSelectconvert (Char(5),@dt, -)+'1-1'--B. The last day of the yearSelectconvert (Char(5),@dt, -)+'12-31'--2. The first or last day of the quarter on which the specified date is located--A. First day of the quarterSelectconvert (datetime,    CONVERT(Char(8),        DATEADD(Month,            DATEPART(Quarter,@dt)*3-Month(@dt)-2,            @dt),         -)+'1')SELECT DATEADD(QQ,DATEDIFF(QQ,0,GETDATE()),0) --B. The last day of the quarter (case judgment method)Selectconvert (datetime,    CONVERT(Char(8),        DATEADD(Month,            DATEPART(Quarter,@dt)*3-Month(@dt),            @dt),         -)    +Casewhendatepart (Quarter,@dt)inch(1,4)         Then' to'ELSE' -'END)--C. Last day of the quarter (direct projection method)Selectdateadd ( Day,-1,    CONVERT(Char(8),        DATEADD(Month,            1+DATEPART(Quarter,@dt)*3-Month(@dt),            @dt),         -)+'1')--3. The first or last day of the month in which the specified date is located--A. First day of the monthSelectconvert (datetime,CONVERT(Char(8),@dt, -)+'1')--B. The last day of the monthSelectdateadd ( Day,-1,CONVERT(Char(8),DATEADD(Month,1,@dt), -)+'1')--C. Last day of the month (easy-to-use error method)Selectdateadd (Month,1,DATEADD( Day,- Day(@dt),@dt))--4. Any day of the week on which the specified date is locatedSelectdateadd ( Day,@number-DATEPART(Weekday,@dt),@dt)--5. Any day of the week on which the specified date is located--A. Sunday as the 1th day of the weekSelectdateadd ( Day,@number-(DATEPART(Weekday,@dt)+@ @DATEFIRST-1)%7,@dt)--B. Monday as the 1th day of the weekSelectdateadd ( Day,@number-(DATEPART(Weekday,@dt)+@ @DATEFIRST-2)%7-1,@dt)

SQL Server learning record gets the first and last day of every quarter of each month

Related Article

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.