sql有关日期的实现

发表于:2007-05-25来源:作者:点击数: 标签:
--************ --在两个日期范围里所跨越那几周返回如:1,2表是第一周和第二周, declare @aa table (date datetime,weekdays int ) declare @i int set @i=datediff(day,@bdate,@edate) while(@i=0) begin insert @aa values (dateadd(day,@i,@bdate),dat

--************
--在两个日期范围里所跨越那几周返回如:1,2表是第一周和第二周,

declare @aa table (date datetime,weekdays int )  
declare @i int   
set @i=datediff(day,@bdate,@edate)   
while(@i>=0)   
begin   
insert @aa   
values (dateadd(day,@i,@bdate),datepart(week,dateadd(day,@i,@bdate)))   
set @i=@i-1   
end 
select weekdays  
into #week 
from @AA group by weekdays

--************
--在日期范围里减去周六、周日的天数
create function a (@Sdate datetime ,@Edate datetime) 
returns   int 
as 
begin 
declare @aa table (date datetime) 
declare @i int 
set @i=datediff(day,@Sdate,@Edate) 
while(@i>=0) 
begin 
insert @aa  
values (dateadd(day,@i,@Sdate)) 
set @i=@i-1 
end 
select @i= count(*)  from @aa where   datepart(weekday,date) not in (1,7)  
return @i 
 
end 

--如:select dbo.A('2004-10-01','2004-10-11')
--返回结果为7

--***********
--输入第几周得到此周的开始、结束日期
declare @FirstDayOfYear datetime--年頭
declare @FirstDayWeekOfYear datetime --第一周的第一天
declare @BDate datetime
declare @EDate datetime

select @FirstDayOfYear= dateadd(yy,datediff(yy,0,getdate()),0)                
select   @FirstDayWeekOfYear=@FirstDayOfYear  - datepart(dw, @FirstDayOfYear)+1

select  @EDate=dateadd(ww,@week,@FirstDayWeekOfYear-1 )
select @BDate=  dateadd(ww,-1,dateadd(dd,1,@EDate)  )

SET @BDate =convert(datetime, convert(char(10),@BDate,101))     
SET @EDate =convert(datetime, convert(char(10),@EDate,101))


原文转自:http://www.ltesting.net