CREATE TABLE #DaysTable(tdays datetime)
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
WITH
CTE_Days AS
(
SELECT DATEADD(month, @month, DATEADD(month, -MONTH(@dataforDate), DATEADD(day, -DAY(@dataforDate) + 1, CAST(FLOOR(CAST(@dataforDate AS FLOAT)) AS DATETIME)))) Days
UNION ALL
SELECT DATEADD(day, 1, Days)
FROM CTE_Days
WHERE Days < DATEADD(day, -1, DATEADD(month, 1, DATEADD(month, @month, DATEADD(month, -MONTH(@dataforDate), DATEADD(day, -DAY(@dataforDate) + 1, CAST(FLOOR(CAST(@dataforDate AS FLOAT)) AS DATETIME))))))
)
insert into #dayatable
select * from
(
SELECT DATEADD(month, @month, DATEADD(month, -MONTH(@dataforDate), DATEADD(day, -DAY(@dataforDate) + 1, CAST(FLOOR(CAST(@dataforDate AS FLOAT)) AS DATETIME)))) Days
UNION ALL
SELECT DATEADD(day, 1, Days)
FROM CTE_Days
WHERE Days < DATEADD(day, -1, DATEADD(month, 1, DATEADD(month, @month, DATEADD(month, -MONTH(@dataforDate), DATEADD(day, -DAY(@dataforDate) + 1, CAST(FLOOR(CAST(@dataforDate AS FLOAT)) AS DATETIME))))))
)
但是这给了我错误。
答案 0 :(得分:1)
纠正我,如果我错了你在插入CTE中已经存在的语句后重复相同的条件,如果是这样的话,你可以简单地写如下:
WITH CTE_Days AS
(
SELECT DATEADD(month, @month, DATEADD(month, -MONTH(@dataforDate), DATEADD(day, -DAY(@dataforDate) + 1, CAST(FLOOR(CAST(@dataforDate AS FLOAT)) AS DATETIME)))) Days
UNION ALL
SELECT DATEADD(day, 1, Days)
FROM CTE_Days
WHERE Days < DATEADD(day, -1, DATEADD(month, 1, DATEADD(month, @month, DATEADD(month, -MONTH(@dataforDate), DATEADD(day, -DAY(@dataforDate) + 1, CAST(FLOOR(CAST(@dataforDate AS FLOAT)) AS DATETIME))))))
)
insert into #DaysTable
select * from CTE_Days;
答案 1 :(得分:0)