如下:
復制代碼 代碼如下:
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