Interview Question of the Week #047 – Logic To Find Weekdays Between Two Dates

I often enjoy seeing interview questions where the contestant has to write SQL Scripts. Here is another such example.

Question: How to find weekdays between two dates?

Answer: Here is a function which can be used to find weekdays between two dates.

CREATE FUNCTION dbo.getDayCount(@startdate date, @enddate date)
RETURNS INT
AS
BEGIN
DECLARE
@count INT = 0
WHILE @startdate<=@enddate
BEGIN
IF
DATEPART(dw,@startdate) > 1 AND DATEPART(dw,@startdate) < 7
BEGIN
SET
@count = @count + 1
END
SET
@startdate = DATEADD(DAY,1,@startdate)
END
RETURN
@count
END
-- Execute Function
SELECT dbo.getDayCount ('10/10/2015', '11/10/2015')

Reference: Pinal Dave (https://blog.sqlauthority.com)

Previous Post
SQL SERVER 2016 – Comparing Execution Plans
Next Post
SQL SERVER – Practical Tips to Reduce SQL Server Database Table Size – Experts Opinion

Related Posts

No results found.

Leave a Reply