sqlserver中獲得月份的天數的辦法分享。本站提示廣大學習愛好者:(sqlserver中獲得月份的天數的辦法分享)文章只能為提供參考,不一定能成為您想要的結果。以下是sqlserver中獲得月份的天數的辦法分享正文
以下:
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