我想获得用户指定的月份天数。我正在使用它,除了2月和闰年之外,它可以工作大部分时间。它显示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
或者如果没有,你能告诉我另一种方法吗?它应该使用@year
和@month
以及代码来查找日期可以是任何日期!
答案 0 :(得分: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);
<强> Example on SQL Fiddle 强>
答案 1 :(得分:1)
这将是一个很好的解决方案。
DECLARE @year INT,@month INT
SET @year = 2011
SET @month = 2
SELECT DAY(EOMONTH(DATEFROMPARTS(@year,@month,1)))
答案 2 :(得分:1)
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
答案 3 :(得分:0)
然后您需要做的就是获取所需的输入,将它们转换为存储在@date中的日期,然后您可以使用that post中的第一个示例而不做任何更改。按原样使用您的代码,它只需要再一行构建,然后是第一个解决方案:
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)))