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