What is the best way to take a date variable in SQL and set it to Beginning of Year and End of Year?
declare @calcDate date = '7/7/2016'
How do I get '1/1/2016' and '12/31/2016' using @calcDate?
What is the best way to take a date variable in SQL and set it to Beginning of Year and End of Year?
declare @calcDate date = '7/7/2016'
How do I get '1/1/2016' and '12/31/2016' using @calcDate?
I would just use datefromparts()
:
select datefromparts(year(@calcdate), 1, 1) as soy,
datefromparts(year(@calcdate), 12, 31) as eoy
Earlier versions of SQL Server require strange date arithmetic. This function is available in SQL Server 2012+ (see here).
DECLARE @calcDate date = '7/7/2016'
SELECT
DATEADD(yy, DATEDIFF(yy,0,@calcDate), 0) AS BeginningOfYear,
DATEADD(yy, DATEDIFF(yy,0,@calcDate) + 1, -1) AS EndOfYear
Seems to me there is no real "calculation" to be done here since the first day of the year is always 1/1 and the last day is always 12/31. We just need to append these to the year in question:
declare @calcDate date = '7/7/2016'
select cast(cast(year(@calcDate) as varchar(4)) + '0101' as date)
select cast(cast(year(@calcDate) as varchar(4)) + '1231' as date)
Result:
2016-01-01
2016-12-31
year
is available in SQL Server 2008 and above.