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:
DECLARE @MonthNo TINYINT = 03 -- set your month
,@WOYEAR SMALLINT = 2018; -- set your year
IF OBJECT_ID('TEMPDB..#TMP') IS NOT NULL
DROP TABLE #TMP
DECLARE @START_DATE DATETIME
,@END_DATE DATETIME
,@CUR_DATE DATETIME
SET @START_DATE = DATEADD(month, @MonthNo - 1, DATEADD(year, @WOYEAR - 1900, 0))
SET @END_DATE = DATEADD(day, - 1, DATEADD(month, @MonthNo, DATEADD(year, @WOYEAR - 1900, 0)))
SET @CUR_DATE = @START_DATE
CREATE TABLE #TMP (
WEEKDAY VARCHAR(10)
,DATE INT
,MONTH VARCHAR(10)
,YEAR INT
,dates VARCHAR(25)
)
WHILE @CUR_DATE <= @END_DATE
BEGIN
INSERT INTO #TMP
SELECT DATENAME(DW, @CUR_DATE)
,DATEPART(DAY, @CUR_DATE)
,DATENAME(MONTH, @CUR_DATE)
,DATEPART(YEAR, @CUR_DATE)
,REPLACE(CONVERT(VARCHAR(9), @CUR_DATE, 6), ' ', '-')
SET @CUR_DATE = DATEADD(DD, 1, @CUR_DATE)
END
SELECT *
FROM #TMP