I want to get all dates by declaring month and year in SQL server.
Can anyone please share easy lines of SQL code to get it.
For example:
You can't get all days just by declaring the month, you need to add the year as well because of leap years:
DECLARE @date DATE = getdate()
;WITH N(N)AS
(SELECT 1 FROM(VALUES(1),(1),(1),(1),(1),(1))M(N)),
tally(N)AS(SELECT ROW_NUMBER()OVER(ORDER BY N.N)FROM N,N a)
SELECT top(day(EOMONTH(@date)))
N day,
dateadd(d,N-1, @date) date
FROM tally
Another different solution(by t@clausen):
DECLARE @month AS INT = 5
DECLARE @Year AS INT = 2016
;WITH N(N)AS
(SELECT 1 FROM(VALUES(1),(1),(1),(1),(1),(1))M(N)),
tally(N)AS(SELECT ROW_NUMBER()OVER(ORDER BY N.N)FROM N,N a)
SELECT N day,datefromparts(@year,@month,N) date FROM tally
WHERE N <= day(EOMONTH(datefromparts(@year,@month,1)))