如下:
复制代码 代码如下:
create function [dbo].[udf_daysinmonth]
(
@date datetime
)
returns int
as
begin
declare @dim as table (m int,dy int)
insert into @dim values
(1,31),(3,31),(5,31),(7,31),(8,31),(10,31),(12,31),
(4,30),(6,30),(9,30),(11,30),
(2,
case when (year(@date) % 4 = 0 and year(@date) % 100 <> 0) or (year(@date) % 400 = 0)
then 29
else 28 end
)
declare @rvalue int
select @rvalue = [dy] from @dim where [m] = month(@date)
return @rvalue
end
go
获取月份天数,以前在博客上也有写过,不过它只是取得二月份的天数。链接如下:http://www.cnblogs.com/insus/articles/2025019.html
现第一眼看见专案中这个函数,总觉它写得不够好的感觉,是否能把它改写得更好些,启发点也是从获取二月份天数的case函数想起的。
因此,我尝试改了,如下:
复制代码 代码如下:
create function [dbo].[udf_daysinmonth]
(
@date datetime
)
returns int
as
begin
return case when month(@date) in (1,3,5,7,8,10,12) then 31
when month(@date) in (4,6,9,11) then 30
else case when (year(@date) % 4 = 0 and year(@date) % 100 <> 0) or (year(@date) % 400 = 0)
then 29
else 28
end
end
end
如果你已经有引过insus.net那个获取二月份天数的自定义函数,也可以参考下面这个版本:
复制代码 代码如下:
create function [dbo].[udf_daysinmonth]
(
@date datetime
)
returns int
as
begin
return case when month(@date) in (1,3,5,7,8,10,12) then 31
when month(@date) in (4,6,9,11) then 30
else [dbo].[daysoffebruary](year(@date))
end
end