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