Quantcast
Channel: SQL Server
Viewing all articles
Browse latest Browse all 3819

Blog Post: T-SQL to Display Weekends Between two Dates

$
0
0
Different ways to find the weekend between two given dates. The SQL requires @begindate and @endate paramteters to be entered in the below SQL Download T-SQL  WeekendBetweenTwoValidDates DECLARE @beginDate Date='20150101', @endDate Date='20150131' DECLARE @Calendar Table (CalendarDate Date Primary key, IsWeekend Bit) WHILE @beginDate = @endDate BEGIN INSERT INTO @Calendar SELECT @beginDate As CalendarDate ,(Case When DATEPART(Weekday, @beginDate) In (7, 1) Then 1 Else 0 End) As IsWeekend Set @beginDate = DateAdd(Day, 1, @beginDate) End SELECT CalendarDate From @Calendar Where IsWeekend = 1 On SQL 2012 or higher version you can use choose function. http://msdn.microsoft.com/en-us/library/hh213019.aspx DECLARE @beginDate Date='20150101', @EndDate Date='20150131' Declare @Calendar Table (CalendarDate Date Primary key, IsWeekend varchar(20)) While @beginDate = @endDate Begin Insert Into @Calendar SELECT @beginDate As CalendarDate, CHOOSE(DATEPART(dw, @beginDate), 'WEEKEND','Weekday', 'Weekday','Weekday','Weekday','Weekday','WEEKEND') Set @beginDate = DateAdd(Day, 1, @beginDate) End Select CalendarDate From @Calendar where IsWeekend='WEEKEND' Ouput:-

Viewing all articles
Browse latest Browse all 3819


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>