程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> 其他數據庫知識 >> 更多數據庫知識 >> 在sql Server自定義一個用戶定義星期函數

在sql Server自定義一個用戶定義星期函數

編輯:更多數據庫知識

文件:.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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved