我想在用户指定月份的天数。 我用这适用于大多数个月,除了二月和闰年。 它显示了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
和代码,找到日可以是任意!
如果您需要从年份和月份做到这一点(假设两者都是整数),你可以创建一个函数像这样:
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提琴
这将是一个很好的解决方案。
DECLARE @year INT,@month INT
SET @year = 2011
SET @month = 2
SELECT DAY(EOMONTH(DATEFROMPARTS(@year,@month,1)))
加雷思解决方案修改为SQL Server 2005
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
然后,所有你需要做的就是把你想要的输入,将它们转换成存储在@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)))