我想知道是否有计算SQL Server 2008中一个月的天数...类似于我写的这个Javascript代码:
function daysInMonth(month, year) {
return new Date(year, month, 0).getDate();
}
var dateForApp = new Date();
var MonthForApp = (dateForApp.getMonth() + 1);
var yearForApp = dateForApp.getFullYear();
var daysofMonth = new Array();
for (var i = 1; i <= daysInMonth(MonthForApp, yearForApp); i++) {
daysofMonth.push(parseInt(i));
} // Resulting in something like this (1,2,3,4,5,6,7,8,9,10,11,12...etc)
我现在需要弄清楚如何在SQL中执行此操作...到目前为止,我有愚蠢的行为:
declare @Date datetime
select @Date = Getdate()
select datepart(dd,dateadd(dd,-1,dateadd(mm,1,cast(cast(year(@Date) as varchar)+'-'+cast(month(@Date) as varchar)+'-01' as datetime))))
这将让我知道这个月有多少天(31),但我现在不太确定如何完成实际的计数......我正在尝试循环等,但没有成功。有没有人有任何想法或他们可以指向我的线索? (我在网上搜索时一无所获)
答案 0 :(得分:1)
您是否尝试过使用DATEDIFF?
答案 1 :(得分:1)
DECLARE @DaysInMonth INT
SET @DaysInMonth = 31
DECLARE @i INT
SET @i = 1
DECLARE @temp TABLE([Days] INT)
WHILE @i <= @DaysInMonth
BEGIN
INSERT INTO @temp
VALUES(@i)
SET @i = @i + 1
END
SELECT *
FROM @temp
答案 2 :(得分:1)
递归CTE可以提供日期表;
declare @date datetime = '01 feb 1969'
declare @days int = datediff(day, dateadd(day, 1 - day(@date), @date),
dateadd(month, 1, dateadd(day, 1 - day(@date), @date)))
;with days(day) as
(
select 1 as day
union all
select day + 1
from days
where day < @days
)
select day from days