1

我想获取用户指定的月份中的天数。我正在使用它,除了二月和闰年之外,它在大多数月份都有效。它显示的是 28 天而不是 29 天。你能解决这个问题吗?

begin
declare @year int
declare @month int
select @year = 2012
select @month = DATEPART(mm,CAST('August'+ ' 2012' AS DATETIME))
select  datediff(day, 
        dateadd(day, 0, dateadd(month, ((@year - 2012) * 12) + @month - 1, 0)),
        dateadd(day, 0, dateadd(month, ((@year - 2012) * 12) + @month, 0))) as number_of_days

end

或者如果不是,你能告诉我另一种方法来做到这一点。它应该使用@yearand@month和代码来查找天数可以是任意的!

4

4 回答 4

3

如果您需要从年和月开始执行此操作(假设两者都是整数),您可以这样创建一个函数:

CREATE FUNCTION dbo.DaysInMonth (@year INT, @Month INT)
RETURNS INT 
AS
BEGIN
    -- FIRST CONVERT THE YEAR AND MONTH TO A DATE BY CASTING TO CHAR
    -- THEN CONCATENATING TO CREATE A STRING IN THE FORMAT yyyyMMdd
    -- THIS DATEFORMAT IS CULTURE INSENSITIVE SO WILL WORK NO MATTER
    -- WHAT YOUR REGIONAL SETTINGS ARE

    DECLARE @Date DATE = CAST(
                            CAST(@Year AS CHAR(4)) 
                            + RIGHT('0' + CAST(@Month AS VARCHAR(2)), 2)
                            + '01' AS DATE);

    -- USE ESTABLISHED METHODS OF GETTING 1ST OF THE MONTH AND FIRST OF 
    -- THE NEXT MONTH AND CALCULATE THE DIFFERENCE
    RETURN DATEDIFF(DAY, 
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @Date), 0),
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @Date) + 1, 0));
END
GO
-- TEST FUNCTION
SELECT  DaysInMonth = dbo.DaysInMonth(2012, 2);

SQL Fiddle 示例

于 2013-06-26T11:50:07.773 回答
2

这将是一个很好的解决方案。

DECLARE @year INT,@month INT

SET @year = 2011
SET @month = 2

SELECT DAY(EOMONTH(DATEFROMPARTS(@year,@month,1)))
于 2014-10-22T11:14:51.327 回答
1

为SQL Server 2005修改的 Gareth解决方案

CREATE FUNCTION dbo.DaysInMonth (@year INT, @Month INT)
RETURNS INT 
AS
BEGIN
    -- FIRST CONVERT THE YEAR AND MONTH TO A DATE BY CASTING TO CHAR
    -- THEN CONCATENATING TO CREATE A STRING IN THE FORMAT yyyyMMdd
    -- THIS DATEFORMAT IS CULTURE INSENSITIVE SO WILL WORK NO MATTER
    -- WHAT YOUR REGIONAL SETTINGS ARE

    DECLARE @Date datetime
    SET @DATE = CAST(
                            CAST(@Year AS CHAR(4)) 
                            + RIGHT('0' + CAST(@Month AS VARCHAR(2)), 2)
                            + '01' AS DATETIME);

    -- USE ESTABLISHED METHODS OF GETTING 1ST OF THE MONTH AND FIRST OF 
    -- THE NEXT MONTH AND CALCULATE THE DIFFERENCE
    RETURN DATEDIFF(DAY, 
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @Date), 0),
            DATEADD(MONTH, DATEDIFF(MONTH, 0, @Date) + 1, 0));
END
GO
于 2015-05-08T09:48:07.200 回答
0

然后,您需要做的就是获取所需的输入,将它们转换为存储在 @date 中的日期,然后您可以使用该帖子中的第一个示例而无需任何更改。按原样使用您的代码,只需要多行转换,然后是第一个解决方案:

declare @year int
declare @month int
declare @date date
select @year = 2012
select @month = DATEPART(mm,CAST('august'+ ' 2012' AS DATETIME))
select @date = cast(cast(@month as varchar(20)) + '/1/' + cast(@year as varchar(4)) as datetime)

select @month, datediff(day, dateadd(day, 1-day(@date), @date),
          dateadd(month, 1, dateadd(day, 1-day(@date), @date)))
于 2013-06-26T11:40:04.607 回答