SQL 获取某月 自然天数

方法1:

create function fn_getDayByYearMonth(@year int,@month int) 
returns int 
begin 
 declare @date datetime 
 declare @day int
 if(@month<>12) 
 begin  
  set @month = @month + 1 
  set @date = cast(cast(@year as varchar)+'-'+cast(@month as varchar)+'-1' as datetime) 
 end 
 if(@month=12) 
 begin 
  set @date = cast(cast(@year as varchar)+'-'+cast(@month as varchar)+'-31' as datetime)
 end  
 set @day = day(@date-1) 
 return @day 
end 

 

go

 

create function fn_getMaxDate(@year int,@month int) 
returns datetime 
begin 
 declare @date datetime 
 declare @day int 
 set @day = dbo.fn_getDayByYearMonth(@year,@month) 
 set @date = cast(cast(@year as varchar)+'-'+cast(@month as varchar)+'-'+cast(@day as varchar) as datetime) 
 return @date 
end

 

 

go

select dbo.fn_getMaxDate(2010,10)

go

方法2:

select day(dateadd(mm,datediff(mm,-1,getdate()),0)-1)

/*
解释:

数据类型 范围 精确度

datetime

1753 年 1 月 1 日到 9999 年 12 月 31 日

3.33 毫秒

smalldatetime

1900 年 1 月 1 日到 2079 年 6 月 6 日

1 分钟

例:datediff(mm,0,getdate())  
0就代表:1900年1月1日。DATEDIFF(MM,0,GETDATE())就是求1900年1月1日到今天相差的月数。以今天(2011.8.3)为例,那么就会返回1339。
而上面采用的是 -1,如: datediff(mm,-1,getdate()),则代表  1900年1月1日到今天相差的月数 +1 = 1340/月
在接着看:
        dateadd(mm,datediff(mm,-1,getdate()),0) 相当于 
1900年1月1日 + 1340/月 = 2011-09-01 00:00:00.000
        day('2011-09-01',-1) 等于 前一个月的最后一天。

datediff(mm, -1, getdate())  => 1340
dateadd(mm, 1340, 0) =>  2011-09-01 00:00:00.000
day('2011-09-01 00:00:00.000', -1)  =>  2011-08-31 00:00:00.000


*/

你可能感兴趣的:(sql,Date,function,Go,2010)