## Select all months bewtween two dates

 Author Message aneel.c SSC-Enthusiastic Group: General Forum Members Points: 161 Visits: 102 Please help me in finding a query to get all months the between two dates. GSquared SSC-Insane Group: General Forum Members Points: 20087 Visits: 9730 The best way to do that is to build a calendar table.The second best way is to use a numbers table.After that, it's a numbers CTE.After that, recursion.Are you in a position where you can build a calendar table? It's just a table of dates, starting from whatever you need and ending whenever you need. For example, a table of dates between 1 Jan 2000 and 31 Dec 2050, is a default that I use quite often. You can then store in it things like which dates are holidays, weekends, etc.If you have a numbers table, you can do a query where you use DateAdd(month) on the numbers table, with the first date being what you add to.If you don't have either of those, and can't build either one, you might be able to build a numbers CTE, where you select row_number in a CTE, and then use that just like a numbers table.If none of those are possible, build a While loop and insert into a temp table (or a table variable if it needs to be a UDF), or build a recursive CTE with a Union All operator. - Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETCProperty of The Thread"Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon Bijal Parekh SSC-Enthusiastic Group: General Forum Members Points: 103 Visits: 352 declare @month table(months varchar(30))declare @date1 datetimedeclare @date2 datetimeset @date1='10/1/2011'set @date2='9/1/2010'declare @year1 intdeclare @year2 intset @year1= year(@date1)set @year2= year(@date2)declare @month1 intdeclare @month2 intset @month1=month(@date1)set @month2=month(@date2)declare @count int declare @monthname datetimeif (@year1<>@year2)begin if @month1=@month2 set @count=12 else if @month1<>@month2 set @count=12-ABS(@month1-@month2)+1if @date1<@date2 set @monthname=@date1else if @date2<@date1 set @monthname=@date2 while @count>0 begin insert @month(months) select datename(month,@monthname) set @monthname=dateadd(mm,1,@monthname) set @count=@count-1 endendif @year1=@year2beginif @month1=@month2 set @count=1else if @month1<>@month2 set @count=ABS(@month2-@month1)+1if @date1<@date2 set @monthname=@date1else if @date2<@date1 set @monthname=@date2 while @count>0 begin insert @month(months) select datename(month,@monthname) set @monthname=dateadd(mm,1,@monthname) set @count=@count-1 endendselect * from @month GSquared SSC-Insane Group: General Forum Members Points: 20087 Visits: 9730 Ouch! Yeah, that piece of code might work, but it hurts to look at!`;with Numbers (Number) as (select row_number() over (order by object_id) from sys.all_objects)select dateadd(month, number, @StartDate)from Numberswhere number <= datediff(month, @StartDate, @EndDate)` - Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETCProperty of The Thread"Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon ganci.mark SSC Eights! Group: General Forum Members Points: 871 Visits: 546 Do the dates always fall within the same year?orCan they be for example 10-20-2008 and 01-23-2009? GSquared SSC-Insane Group: General Forum Members Points: 20087 Visits: 9730 The Numbers version can work across years, just have to have enough rows in the Numbers CTE (you can get quite a few with just sys.all_objects; if that's not enough, do a cross join). The "I've declared ten-million variables" version can work across a single year, so far as I can tell. - Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETCProperty of The Thread"Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon ganci.mark SSC Eights! Group: General Forum Members Points: 871 Visits: 546 Good one SS!might want to modify it slightly to include starting month?;with Numbers (Number) as (select row_number() over (order by object_id) from sys.all_objects)select dateadd(month, number-1, @StartDate)from Numberswhere number-1<= datediff(month, @StartDate, @EndDate) Jeff Moden SSC Guru Group: General Forum Members Points: 70472 Visits: 40737 GSquared (1/29/2009)Ouch! Yeah, that piece of code might work, but it hurts to look at!`;with Numbers (Number) as (select row_number() over (order by object_id) from sys.all_objects)select dateadd(month, number, @StartDate)from Numberswhere number <= datediff(month, @StartDate, @EndDate)`Ahhhhh.... MUCH better. No loops... no recurrsion in the CTE... nice tight code...The only thing that may be a problem is that (I believe... haven't tested the code) it looks like the day of the startdate and enddate are preserved instead of the whole month being included. Guess it all depends on what the op actually needs. --Jeff ModenRBAR is pronounced ree-bar and is a Modenism for Row-By-Agonizing-Row.First step towards the paradigm shift of writing Set Based code: Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column.If you think its expensive to hire a professional to do the job, wait until you hire an amateur. -- Red Adair Helpful Links:How to post code problemsHow to post performance problemsForum FAQs GSquared SSC-Insane Group: General Forum Members Points: 20087 Visits: 9730 It'll depend on what he's looking for. If he needs the start month, it needs a -1 on the row_number function, so that it starts with 0 instead of 1. If he needs the names of the months, that'll need to be added to the final select. If he needs it to give the first day of each month, that'll require a slight modification to the final select. And so on. Since I don't have those details, I set up a skeleton, and the OP can either flesh it out, or ask questions about the details, or (all to common) never speak up again and we won't know what was actually needed. - Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETCProperty of The Thread"Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon feroz_tt SSC-Enthusiastic Group: General Forum Members Points: 158 Visits: 70 Hi All,I'm getting some problem here;with Numbers (Number) as (select row_number() over (order by object_id) from sys.all_objects)select dateadd(month, number, '2014-09-01')from Numberswhere number <= datediff(month, '2014-09-01', '2016-03-31')Low no of months.Select datediff(month, '2014-09-01', '2016-03-31')it should give 31 instead of 18.I don't understand where i'm wrong

## Permissions

 You can't post new topics. You can't post topic replies. You can't post new polls. You can't post replies to polls. You can't edit your own topics. You can't delete your own topics. You can't edit other topics. You can't delete other topics. You can't edit your own posts. You can't edit other posts. You can't delete your own posts. You can't delete other posts. You can't post events. You can't edit your own events. You can't edit other events. You can't delete your own events. You can't delete other events. You can't send private messages. You can't send emails. You can read topics. You can't vote in polls. You can't upload attachments. You can download attachments. You can't post HTML code. You can't edit HTML code. You can't post IFCode. You can't post JavaScript. You can post emoticons. You can't post or upload images.

##### Select a forum
 SQL Server 2016      SQL Server 2016 - Administration      SQL Server 2016 - Development and T-SQL SQL Server 2014      Administration - SQL Server 2014      Development - SQL Server 2014 SQL Server 2012      SQL 2012 - General      SQL Server 2012 - T-SQL SQL Server vNext      SQL Server 14 - Administration      SQL Server 14 - Development SQL Server 2008      SQL Server 2008 - General      T-SQL (SS2K8)      June 2007 CTP      Working with Oracle      July CTP      SQL Server Newbies      Security (SS2K8)      SQL Server 2008 High Availability      SQL Server 2008 Administration      Data Corruption (SS2K8 / SS2K8 R2)      SQL Server 2008 Performance Tuning Cloud Computing      SQL Azure - Development      SQL Azure - Administration      Amazon AWS and other cloud vendors      General Cloud Computing Questions Reporting Services      Reporting Services      Reporting Services 2005 Administration      Reporting Services 2005 Development      Reporting Services 2008/R2 Administration      Reporting Services 2008 Development      SSRS 2012      SSRS 2014      SSRS 2016 Programming      Connecting      General      SMO/RMO/DMO      XML      Service Broker      Powershell      Testing      TFS/Data Dude/DBPro      SSDT      Continuous Integration, Deployment, and Delivery      R Services and R Language Data Warehousing      Integration Services      Strategies and Ideas      Analysis Services      Data Transformation Services (DTS)      Performance Point      Data Mining      PowerPivot      R language      Machine Learning Database Design      Disaster Recovery      Design Ideas and Questions      Relational Theory      Hardware      Virtualization SQLServerCentral.com      Anything that is NOT about SQL!      Contests!      Editorials      SQLServerCentral.com Announcements      SQLServerCentral.com Website Issues      Suggestions      Tag Issues with Content      Podcast Feedback      SQLServerCentral.com Test Forum      Articles Requested SQL Server 2005      Administering      Backups      Business Intelligence      CLR Integration and Programming.      Data Corruption      Development      Working with Oracle      SQL Server 2005 Compact Edition      SQL Server 2005 General Discussion      SQL Server 2005 Security      SQL Server 2005 Strategies      SS2K5 Replication      SQL Server Express      SQL Server 2005 Performance Tuning      SQL Server 2005 Integration Services      T-SQL (SS2K5)      SQL Server Newbies SQL Server 7,2000      Administration      Backups      Data Corruption      General      Globalization      In The Enterprise      Working with Oracle      Security      Strategies      SQL Server Newbies      Service Packs      SQL Server CE      Performance Tuning      Replication      Sarbanes-Oxley      T-SQL      SQL Server Agent SQL Server and other platforms      MySQL      Oracle      PostgreSQL      DB2      SQL Server and Sharepoint Older Versions of SQL (v6.5, v6.0, v4.2)      Older Versions of SQL (v6.5, v6.0, v4.2) Career      Certification      Employers and Employees      Events      Job Postings      Resumes and Job Hunters      Presentations and Speaking      Retired Members Testing Center      Question of the Day (QOD)      SQL Server Security Skills Microsoft Access      Microsoft Access Products and Books      Third Party Products         Extreme Technologies.         Innovartis         Embarcadero         SQL Sentry         Sonasoft         SQLCentric         Golden Gate Software         CA         Idera         Red Gate Software         Lumigent         Quest Software         ApexSQL      Discussions about Books         Discuss Programming Books          Discuss XML Books          Discuss T-SQL Books          Discuss Data Warehousing Books          Discuss SQL Server 2000 Books         Discuss DTS Books          Discuss SQL Server 7.0 Books Notification Services      Administration Article Discussions Future Versions      SQL 12