在sql Server自定义一个用户定义星期函数

时间:2021-05-02

文件:.wmv;大小:19,535KB;长度:00:26:39。
下载地址:SqlFunction_udf_Week.rar
以下内容于20120105更新:
2012年刚到,开发的软件使用这个函数发现bug。2012年第一周应该是2012-01-01至2012-01-07,但此函数却把2012-01-08至2012-01-14当作第一周。

就此bug对此函数修改如下:

复制代码 代码如下:


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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章