SQL Server Stored Procedure that counts the number of weeks

Source: Internet
Author: User
-- Used to count the number list of Sunday to Saturday within the specified date range
If exists (SELECT * FROM dbo. sysobjects WHERE id = OBJECT_ID (n' [dbo]. [usp_GetWeekDayCount] ') and objectproperty (id, n' IsProcedure') = 1)
Drop proc [dbo]. [usp_GetWeekDayCount]
GO

Create proc [dbo]. [usp_GetWeekDayCount]
@ BeginDate DATETIME, @ EndDate DATETIME
AS
Set nocount on;

DECLARE @ WeekDay TABLE
(
[Index] tinyint not null primary key,
[Name] NVARCHAR (20) not null,
[Count] INT
);

DECLARE @ DateFirst DATETIME, @ DateLast DATETIME;
SELECT @ DateFirst = DATEADD (week, DATEDIFF (week, 0, GETDATE (), 0)
, @ DateLast = DATEADD (week, DATEDIFF (week, 0, GETDATE () + 1, 0 );

WHILE @ DateFirst <@ DateLast
BEGIN
Insert into @ WeekDay ([Index], [Name], [Count])
VALUES (DATEPART (weekday, @ DateFirst), DATENAME (weekday, @ DateFirst), 0 );

SET @ DateFirst = DATEADD (day, 1, @ DateFirst );
END;

SELECT @ DateFirst = DATEADD (week, DATEDIFF (week, 0, @ BeginDate) + 1, 0)
, @ DateLast = DATEADD (week, DATEDIFF (week, 0, @ EndDate), 0 );
IF @ DateLast <@ DateFirst
UPDATE @ WeekDay
SET [Count] = [Count] + 1
WHERE [Index]> = DATEPART (weekday, @ BeginDate)
AND [Index] <= DATEPART (weekday, @ EndDate );
ELSE
BEGIN
UPDATE @ WeekDay
SET [Count] = [Count] + DATEDIFF (day, @ DateFirst, @ DateLast)/7;

UPDATE @ WeekDay
SET [Count] = [Count] + 1
WHERE [Index]> = DATEPART (weekday, @ BeginDate );

UPDATE @ WeekDay
SET [Count] = [Count] + 1
WHERE [Index] <= DATEPART (weekday, @ EndDate );
END;

-- Unified with. NET weekly index (0-6)
UPDATE @ WeekDay
SET [Index] = [Index]-1;

SELECT *
FROM @ WeekDay;

Set nocount off;
GO

 

 

 

 

Call example:

 

 

EXEC usp_GetWeekDayCount '2017-04-01 ', '2017-04-30'
Result:
Index Name Count
------------------------------------
0 Sunday 5
1 Monday 5
2 Tuesday 4
3 Wednesday 4
4 Thursday 4
5 Friday 4
6 Saturday 4

 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.