欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-04 12:23:22
文件:.wmv;大小:19,535kb;长度:00:26:39。 下载地址:sqlfunction_udf_week.rar以下内容于20120105更新: 2012年刚到...
文件:.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