The following code gets the number of days for a specific month set in @month
DECLARE @month tinyint
, @Days varchar(max)
SET @month = 1 -January
;WITH DaysInMonth
AS
(
SELECT DATEADD(month, @month, DATEADD(month, -MONTH(GETDATE()), DATEADD(day, -DAY(GETDATE()) + 1, CAST(FLOOR(CAST(GETDATE() AS float)) AS datetime)))) D
UNION ALL
SELECT DATEADD(day, 1, D)
FROM DaysInMonth
WHERE D < DATEADD(day, -1, DATEADD(month, 1, DATEADD(month, @month, DATEADD(month, -MONTH(GETDATE()), DATEADD(day, -DAY(GETDATE()) + 1, CAST(FLOOR(CAST(GETDATE() AS float)) AS datetime))))))
)
SELECT
@Days = substring((SELECT ( ', ' + CONVERT(varchar(2), D, 104))
FROM DaysInMonth
FOR XML PATH( '' )
), 3, 1000 ) FROM DaysInMonth
SELECT @Days
I am getting the following output in a single column:
01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
How can I get these values in different columns?.
The main aim for get this query is to join or union with another query that contains records marked with 1 or 0 set to a specific date. The final query will output a result similar to the one a have below but, for the full month sent in the parameter.
July 28 29 30 31 01 02 03
NULL Monday Tuesday Wednesday Thursday Friday Saturday Sunday
Jhon 1 0 1 0 1 0 0
Any other solution to get around similar output is welcome.Thank you
Best Answer
For the modifications to the question, here is a modified query:
yielding this:
fro the original question: Not quite sure what this achieves, but the following works nicely:
to yield this:
or with
@month int = '20140210' -- February
we get:No RDBMS tagged, so used SQL Server syntax above.