sqlserver中获取月份的天数的方法分享

前端之家收集整理的这篇文章主要介绍了sqlserver中获取月份的天数的方法分享前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

如下:
<div class="codetitle"><a style="CURSOR: pointer" data="20074" class="copybut" id="copybut20074" onclick="doCopy('code20074')"> 代码如下:

<div class="codebody" id="code20074">
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,(5,(7,(8,(10,(12,
(4,30),(6,(9,(11,
(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函数想起的。
因此,我尝试改了,如下:
<div class="codetitle"><a style="CURSOR: pointer" data="11788" class="copybut" id="copybut11788" onclick="doCopy('code11788')"> 代码如下:
<div class="codebody" id="code11788">
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那个获取二月份天数的自定义函数,也可以参考下面这个版本:
<div class="codetitle"><a style="CURSOR: pointer" data="89761" class="copybut" id="copybut89761" onclick="doCopy('code89761')"> 代码如下:
<div class="codebody" id="code89761">
CREATE FUNCTION [dbo].[udf_DaysInMonth]
(
@Date DATETIME
)
RETURNS INT
AS
BEGIN
RETURN CASE WHEN MONTH(@Date) IN (1,11) THEN 30
ELSE [dbo].DaysOfFebruary
END
END

原文链接:https://www.f2er.com/mssql/63961.html
天数天数月份月份

猜你在找的MsSQL相关文章