Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm using sql server 2005 and i need to generate days in sql using Month And YEar only in sql


I expect the answer is
My input to sql is '03/2019'

Expected Output:-
01-03-2019
02-03-2019
'
'
'
'
'
'

'
'31-03-2019
How to genarate this?

What I have tried:

I already used with start and end Date to generate days

SQL
declare @StartDate as datetime
declare @EndDate as datetime

set @StartDate='03/01/2019'
set @EndDate='03/06/2019'

;WITH    AllDays      
AS ( SELECT   @StartDate AS EntryDate, (CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END) AS [issunday]      
   UNION ALL      
   SELECT   DATEADD(DAY, 1, EntryDate),(CASE WHEN DATENAME(dw,  DATEADD(DAY, 1, EntryDate)) = 'Sunday' THEN 1 ELSE 0 END)      
   FROM     AllDays      
   WHERE    EntryDate < @EndDate )      
SELECT EntryDate, [issunday] into #tempX   
FROM   AllDays OPTION (MAXRECURSION 0)  

Select * from #TempX
Posted
Updated 8-Mar-19 19:59pm
v3
Comments
[no name] 9-Mar-19 0:20am    
Try "something" because no one has a clue how you plan to get the "input" in or the "output" out.
Patrice T 9-Mar-19 0:26am    
Show your code.
Patrice T 9-Mar-19 0:59am    
Use Improve question to update your question.
So that everyone can pay attention to this information.
[no name] 9-Mar-19 1:19am    
updated sir

1 solution

Instead of regenerating it each time, I'd pregenerate it: two tables containing two columns: Month and Day, with a row for each day of the year (the second table is for leap years)
Then it's just a case of splitting the date into @MONTH and @YEAR, then using a simple SELECT on the correct table:
SQL
SELECT Day + '-' + Month + '-' + @YEAR FROM MonthNonLeapYear WHERE Month=@Month
Much more efficient than loops or CTEs and temporary tables.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900