日期:2014-05-17 浏览次数:20686 次
->? declare @dt datetime set @dt='2012-08-21' select qfrq between convert(varchar(7),dateadd(month,-1,@dt)),120)+'-25' and @dt from tab
------解决方案--------------------
declare @d0 datetime set @d0='1900-1-25' declare @time datetime set @time='2011-1-1' --用偏移量计算 select case when DAY(@time)>=25 then DATEADD(MONTH,DATEDIFF(month,@d0,@time),@d0) else DATEADD(MONTH,DATEDIFF(month,@d0,@time)-1,@d0) end
------解决方案--------------------
/*创建Nums表,1W行 */ CREATE TABLE dbo.Nums(n INT NOT NULL PRIMARY KEY); DECLARE @max AS INT, @rc AS INT; SET @max = 10000; SET @rc = 1; INSERT INTO Nums VALUES(1); WHILE @rc * 2 <= @max BEGIN INSERT INTO dbo.Nums SELECT n + @rc FROM dbo.Nums; SET @rc = @rc * 2; END INSERT INTO dbo.Nums SELECT n + @rc FROM dbo.Nums WHERE n + @rc <= @max; GO /*函数用于返回时间的月份序列,类似方法可以产生日序列,周序列 等等 参数:@s 开始时间 @e 结束时间 *磊仔 2012年5月29日创建 */ Create function dbo.fn_DayList(@s as datetime,@e as datetime) returns table as return with CET1 AS ( SELECT cast(convert(varchar(6),dateadd(mm, n - 1,@s) ,112) as int) as [Month],--月序列 dateadd(dd,25,dateadd(mm,-1,dateadd(d,datediff(d,0,dateadd(mm, n - 1,@s)),0) - DATEPART(dd, dateadd(mm, n - 1,@s))+1))as StartT, dateadd(dd,25,dateadd(d,datediff(d,0,dateadd(mm, n - 1,@s)),0) - DATEPART(dd, dateadd(mm, n - 1,@s))+1) as EndT FROM dbo.Nums WHERE n <= DATEDIFF(mm, @s, @e) )SELECT * FROM CET1 GO --创建完以上表值函数后就可轻松调用,且性能极佳 declare @time datetime set @time='2011-7-25' select StartT, @Time as NowTime from dbo.fn_DayList('19000101','20500101') where StartT <= @Time and EndT > @Time