最后我得到了我的答案。
USE [Database]
GO
/****** Object: UserDefinedFunction [dbo].[getNextDay] Script Date: 12/28/2012 17:10:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE function [dbo].[getNextDay](@SDate datetime, @Rec varchar(max))
returns datetime
as
BEGIN
--Find the next day based on Condition
Declare @SecArg varchar(max)
Declare @NYear varchar(max)
Declare @NMonth varchar(max)
Declare @NWeek varchar(max)
Declare @NDay varchar(max)
select @NYear = substring(@rec,0,CHARINDEX('_',@rec))
SET @REC = SUBSTRING(@rec,CHARINDEX('_',@rec)+1,LEN(@REC))
select @NMonth = substring(@rec,0,CHARINDEX('_',@rec))
SET @REC = SUBSTRING(@rec,CHARINDEX('_',@rec)+1,LEN(@REC))
select @NWeek = substring(@rec,0,CHARINDEX('_',@rec))
SET @REC = SUBSTRING(@rec,CHARINDEX('_',@rec)+1,LEN(@REC))
Declare @NewDate datetime
set @NewDate = @SDate
if (@NYear != 0 or @NYear != '')
begin
set @SDate = DateAdd(Year,Convert(int,@Nyear),@SDate)
end
if (@NMonth != 0 or @NMonth != '')
begin
set @SDate = DateAdd(Month,Convert(int,@NMonth),@SDate)
end
return Convert(varchar, dbo.getWeekDay(Convert(int,@NWeek),Convert(Int,@rec),DATEADD(dd,-(DAY(@SDate)-1),@SDate)),120)
end
现在我创建了另一个函数 getWeekDay 来查找特定月份的特定星期几
USE [Database]
GO
/****** Object: UserDefinedFunction [dbo].[getWeekDay] Script Date: 12/28/2012 17:15:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE function [dbo].[getWeekDay]( @var_weeknum int, @var_weekday int, @var_date datetime)
returns datetime
as
BEGIN
declare @cnt int
declare @startDay int
declare @DayDiffrence int
declare @ReturnDate datetime
set @cnt = 1
set @startday = datepart(dw, dateadd(mm, datediff(mm, 0, @var_Date),0))
set @DayDiffrence = @var_weekday - @startday
set @ReturnDate = dateadd(mm, datediff(mm, 0, @var_date),0)
if(@DayDiffrence > 0)
begin
set @ReturnDate = dateadd(d,@DayDiffrence,@ReturnDate)
set @ReturnDate = dateadd(wk,@var_weeknum - 1,@ReturnDate)
end
else
begin
set @ReturnDate = dateadd(d,7 - (@DayDiffrence * -1),@ReturnDate)
set @ReturnDate = dateadd(wk,@var_weeknum - 1,@ReturnDate)
end
return @ReturnDate
end
现在终于我通过一个查询得到了答案
select dbo.getNextDay('2012-07-01','0_2_3_3')
In this my date is 2012-07-01
my condition is every 0 year, 2 month, and 3rd week and 3rd dayofweek.
so this will return 2012-09-18
感谢www.google.com和blog.sqlauthority.com
也感谢我的 Stackoverflow 朋友...... :)