Customizing a user-defined week function in SQL Server _mssql

Source: Internet
Author: User
Tags datetime
File:. wmv; Size: 19,535kb; Length: 00:26:39.
Download Address: Sqlfunction_udf_week.rar
The following is updated on 20120105:
2012 just arrived, the software developed uses this function to discover bugs. The first week of 2012 should be 2012-01-01 to 2012-01-07, but this function treats 2012-01-08 to 2012-01-14 as the first week.

Modify this function as follows for this bug:
Copy Code code as follows:

SET ANSI_NULLS on
Go
SET QUOTED_IDENTIFIER ON
Go
ALTER FUNCTION [dbo]. [Udf_week]
(
@StartYear INT,
@EndYear INT
)
RETURNS @Week TABLE ([Weekid] INT IDENTITY (1,1) PRIMARY key,[year] [int] null,[week] [int] null,[startdate] [DATETIME] NULL , [EndDate] [DATETIME] NULL)
As
BEGIN
DECLARE @YearStartDate DATETIME
DECLARE @YearEndDate DATETIME
DECLARE @WeekStartDate DATETIME
DECLARE @WeekEndDate DATETIME
DECLARE @Weeks INT

While @StartYear <= @EndYear
BEGIN
SET @YearStartDate = cast ((CAST (@StartYear as VARCHAR (4)) + ' -01-01 ') as DATETIME)
SET @YearEndDate = cast ((CAST (@StartYear as VARCHAR (4)) + ' -12-31 ') as DATETIME)
SET @Weeks = 1

IF DATEPART (DW, @YearStartDate) > 4
SET @YearStartDate = DATEADD (Day, (8-datepart (DW, @YearStartDate)), @YearStartDate)
ELSE
SET @YearStartDate = DATEADD (Day, (DATEPART (DW, @YearStartDate)-1), @YearStartDate)

SET @WeekStartDate = @YearStartDate
SET @WeekEndDate = DATEADD (day,6, @WeekStartDate)
While DATEDIFF (day, @WeekStartDate, @YearEndDate) >= 4
BEGIN
INSERT into @Week ([year],[week],[startdate],[enddate]) VALUES (@StartYear, @Weeks, @WeekStartDate, @WeekEndDate)
SET @Weeks = @Weeks + 1
SET @WeekStartDate = @WeekStartDate + 7
SET @WeekEndDate = @WeekEndDate + 7
End
SET @StartYear = @StartYear + 1
End
Return
End
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.