## Get particular day between two dates

 Author Message abhas SSC Eights! Group: General Forum Members Points: 906 Visits: 664 Hi All,I want to list Dates for particular day between two dates.for eg. if user enters 08/01/2014 and 08/31/2014 with value 0 then all the Sundays and related dates should be display.if above contamination with 1 then all Mondays,Kindly help.ThanksAbhas abhas SSC Eights! Group: General Forum Members Points: 906 Visits: 664 Hi All,I want to list Dates for particular day between two dates.for eg. if user enters 08/01/2014 and 08/31/2014 with value 0 then all the Sundays and related dates should be display.if above Combination with 1 then all Mondays date,Kindly help.ThanksAbhas kherald69 SSC-Addicted Group: General Forum Members Points: 414 Visits: 576 You can use a recursive common table expression to achieve this.`DECLARE @startDate DATETIME = '8/1/2014'DECLARE @endDate DATETIME = '8/31/2014'DECLARE @dayOfWeek INT = 1 -- 1=Sun, 7=Sat;WITH cte_Recursion AS( SELECT @startDate AS [Date] UNION ALL SELECT DATEADD(DAY, 1, [Date]) FROM cte_Recursion WHERE [Date] < @endDate)SELECT [Date]FROM cte_RecursionWHERE DATEPART(WEEKDAY, [Date]) = @dayOfWeekOPTION (MAXRECURSION 0) -- MaxRecursion 0 is needed when dates are more than 100 days apart` Jack Corbett SSC-Forever Group: General Forum Members Points: 41933 Visits: 14925 kherald provided a solution. Here's my take which still lets you use 0 for Sunday instead of 1 and also takes into account the Language setting of your SQL Server because some languages (actually most in the version of SQL Server I have installed) use Monday as day 1 not Sunday. You can combine both solutions to make it fit your purposes:`DECLARE @StartDate DATE = '2014-08-01', @EndDate DATE = '2014-08-31', @DayNo TINYINT = 6;/* this is a virtual numbers/tally table that is used to get all the days between the days. If you already have a calendar table or a table that hasthe dates you are querying this isn't necessary */ WITH nums AS ( SELECT ROW_NUMBER() OVER (ORDER BY ( SELECT NULL )) - 1 AS N FROM sys.all_columns AS AC ), Calendar AS ( SELECT CONVERT(DATE, DATEADD(DAY, n, @StartDate)) AS theDate FROM nums ), WeekDays AS ( SELECT *, /* figure what day is the first day of the week. This setting is controlled by the language of the SQL Server and you can see the values for DateFirst in sys.syslanguages */ CASE @@DateFirst /* First day of week is monday (1) and last day of week is Sunday (7)*/ WHEN 1 THEN CASE DATEPART(WEEKDAY, theDate) WHEN 7 THEN 0 ELSE DATEPART(WEEKDAY, theDate) END /* 1 and 7 are the only options for @@DATEFIRST currently so Sunday is first day of week when @@DATEFIRS isn't 1 */ ELSE DATEPART(WEEKDAY, theDate) - 1 END AS DayNo, DATENAME(WEEKDAY, theDate) AS DayName FROM Calendar ) SELECT * FROM WeekDays WHERE WeekDays.theDate BETWEEN @StartDate AND @EndDate AND WeekDays.DayNo = @DayNo;` Jack CorbettApplications Developer Don't let the good be the enemy of the best. -- Paul FlemingAt best you can say that one job may be more secure than another, but total job security is an illusion. -- Rod at workCheck out these links on how to get faster and more accurate answers: Forum Etiquette: How to post data/code on a forum to get the best helpNeed an Answer? Actually, No ... You Need a QuestionHow to Post Performance ProblemsCrosstabs and Pivots or How to turn rows into columns Part 1Crosstabs and Pivots or How to turn rows into columns Part 2 Jeff Moden SSC Guru Group: General Forum Members Points: 202966 Visits: 41947 kherald69 (8/8/2014)You can use a recursive common table expression to achieve this.That's a recursive CTE that counts. Please see the following article for why that's a bad idea even for small date ranges.http://www.sqlservercentral.com/articles/T-SQL/74118/ --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 Jack Corbett SSC-Forever Group: General Forum Members Points: 41933 Visits: 14925 Jeff Moden (8/8/2014)kherald69 (8/8/2014)You can use a recursive common table expression to achieve this.That's a recursive CTE that counts. Please see the following article for why that's a bad idea even for small date ranges.http://www.sqlservercentral.com/articles/T-SQL/74118/You can use the Itzik style cross join to replace reading sys.all_columns to get the numbers cte I created in my solution and get rid of all reads in my solution. Like this:`SET STATISTICS IO ON;DECLARE @StartDate DATE = '2014-08-01', @EndDate DATE = '2014-08-31', @DayNo TINYINT = 6;/* this is a virtual numbers/tally table that is used to get all the days between the days. If you already have a calendar table or a table that hasthe dates you are querying this isn't necessary */WITH E1(N) AS ( SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 ), -- 1*10^1 or 10 rows E2(N) AS ( SELECT 1 FROM E1 a, E1 b ), -- 1*10^2 or 100 rows E4(N) AS ( SELECT 1 FROM E2 a, E2 b ), -- 1*10^4 or 10,000 rows E8(N) AS ( SELECT 1 FROM E4 a, E4 b ), -- 1*10^8 or 100,000,000 rows nums AS ( SELECT TOP (4000) ROW_NUMBER() OVER (ORDER BY ( SELECT NULL )) - 1 AS N FROM E8 ), Calendar AS ( SELECT CONVERT(DATE, DATEADD(DAY, n, @StartDate)) AS theDate FROM nums ), WeekDays AS ( SELECT *, /* figure what day is the first day of the week. This setting is controlled by the language of the SQL Server and you can see the values for DateFirst in sys.syslanguages */ CASE @@DateFirst /* First day of week is monday (1) and last day of week is Sunday (7)*/ WHEN 1 THEN CASE DATEPART(WEEKDAY, theDate) WHEN 7 THEN 0 ELSE DATEPART(WEEKDAY, theDate) END /* 1 and 7 are the only options for @@DATEFIRST currently so Sunday is first day of week when @@DATEFIRS isn't 1 */ ELSE DATEPART(WEEKDAY, theDate) - 1 END AS DayNo, DATENAME(WEEKDAY, theDate) AS DayName FROM Calendar ) SELECT * FROM WeekDays WHERE WeekDays.theDate BETWEEN @StartDate AND @EndDate AND WeekDays.DayNo = @DayNo;GODECLARE @StartDate DATE = '2014-08-01', @EndDate DATE = '2014-08-31', @DayNo TINYINT = 6;;WITH cte_Recursion AS ( SELECT @startDate AS [Date] UNION ALL SELECT DATEADD(DAY, 1, [Date]) FROM cte_Recursion WHERE [Date] < @endDate ) SELECT [Date] FROM cte_Recursion WHERE DATEPART(WEEKDAY, [Date]) = @DayNoOPTION (MAXRECURSION 0) -- SET STATISTICS IO OFF;`This is an interesting situation where, if you tune based on execution plan, the recursive cte looks better because if you run both in a batch the recursive cte solution says it's cost is 0% of the batch even though the top solution does 0 reads and the recursive cte does 187. The reason is that no matter how many rows you need to return the cost estimate for the recursive CTE remains the same. For instance if you set the StartDate to 0001-08-01 and leave the EndDate as 2014-08-31 then the recursive CTE (on my laptop) takes ~6500 ms adn the virtual tally table solution takes ~900 ms. Jack CorbettApplications Developer Don't let the good be the enemy of the best. -- Paul FlemingAt best you can say that one job may be more secure than another, but total job security is an illusion. -- Rod at workCheck out these links on how to get faster and more accurate answers: Forum Etiquette: How to post data/code on a forum to get the best helpNeed an Answer? Actually, No ... You Need a QuestionHow to Post Performance ProblemsCrosstabs and Pivots or How to turn rows into columns Part 1Crosstabs and Pivots or How to turn rows into columns Part 2 abhas SSC Eights! Group: General Forum Members Points: 906 Visits: 664 Hi All,Thank you so much. All solutions are suitable.Thank yoy very much. ThanksAbhas. Michael Valentine Jones SSChampion Group: General Forum Members Points: 13651 Visits: 11848 Using the date table function on the link below, here are the queries you can use. Date Table Function F_TABLE_DATEhttp://www.sqlteam.com/forums/topic.asp?TOPIC_ID=61519`select Sunday = [Date]from F_TABLE_DATE('08/01/2014','08/31/2014') where -- Select Sunday ISO_DAY_OF_WEEK = 7select Monday = [Date]from F_TABLE_DATE('08/01/2014','08/31/2014') where -- Select Monday ISO_DAY_OF_WEEK = 1`Results:`Sunday-----------------------2014-08-03 00:00:00.0002014-08-10 00:00:00.0002014-08-17 00:00:00.0002014-08-24 00:00:00.0002014-08-31 00:00:00.000Monday-----------------------2014-08-04 00:00:00.0002014-08-11 00:00:00.0002014-08-18 00:00:00.0002014-08-25 00:00:00.000` Ed Wagner SSC-Forever Group: General Forum Members Points: 43882 Visits: 10831 Jack's solution made me think of this:`declare @dtmStart datetime = '06/01/2014', @dtmEnd datetime = '09/01/2014';with dates_in_range(date_date, date_name) as ( select DATEADD(day, t.N - 1, @dtmStart), datename(weekday, DATEADD(day, t.N - 1, @dtmStart)) from dbo.Tally t where t.N < DATEDIFF(day, @dtmStart, @dtmEnd) + 1)select date_date, date_name from dates_in_range where date_name = 'Wednesday';`You need to have a tally table or use Itzik's approach like Jack did to do it. If you aren't familiar with Tally tables yet, check out the article in my signature. They'll change the way you look at data. Tally Tables - Performance PersonifiedString Splitting with True PerformanceBest practices on how to ask questions LutzM SSC-Insane Group: General Forum Members Points: 22273 Visits: 13559 Expanding on Jacks solution, but eliminating the need to "hope" for @@DateFirst being either 1 or 0, here's an approach that's totally independent on the setting of @@DateFirst.the biggest difference is the way to calculate DayNo:DATEDIFF(dd,-1,theDate)%7 AS DayNo,This code snippet is based on the fact that "day Zero" = 1900-01-01, which is a Monday.The Modulo 7 will return the number of weekdays between 1900-01-01 an theDate, Zero, if theDate is a Monday and 6 if theDate is Sunday.By shifting the day using -1 it'll start with Zero for Sunday to 6 for Saturday.This code is also independent of any language setting (whereas Ed's solution for instance will fail if there's a SET LANGUAGE "GERMAN" is involved before his code).@Jack and Ed: I'm sorry, but I'm a strong advocate against any form of non-deterministic date functions that'll rely on DATEFIRST and/or LANGUAGE settings. At least as long as there are alternatives available ;-)`DECLARE @StartDate DATE = '20140801', @EndDate DATE = '20140831', @DayNo TINYINT = 0;/* this is a virtual numbers/tally table that is used to get all the days between the days. If you already have a calendar table or a table that hasthe dates you are querying this isn't necessary */WITH E1(N) AS ( SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 ), -- 1*10^1 or 10 rows E2(N) AS ( SELECT 1 FROM E1 a, E1 b ), -- 1*10^2 or 100 rows E4(N) AS ( SELECT 1 FROM E2 a, E2 b ), -- 1*10^4 or 10,000 rows E8(N) AS ( SELECT 1 FROM E4 a, E4 b ), -- 1*10^8 or 100,000,000 rows nums AS ( SELECT TOP (4000) ROW_NUMBER() OVER (ORDER BY ( SELECT NULL )) - 1 AS N FROM E8 ), Calendar AS ( SELECT CONVERT(DATE, DATEADD(DAY, n, @StartDate)) AS theDate FROM nums ), WeekDays AS ( SELECT *, DATEDIFF(dd,-1,theDate)%7 AS DayNo, DATENAME(WEEKDAY, theDate) AS DayName FROM Calendar ) SELECT * FROM WeekDays WHERE WeekDays.theDate BETWEEN @StartDate AND @EndDate AND WeekDays.DayNo = @DayNo;` LutzA pessimist is an optimist with experience. How to get fast answers to your question How to post performance related questionsLinks for Tally Table , Cross Tabs and Dynamic Cross Tabs , Delimited Split Function