我想在SQL Server中的CTE返回的@temp或#table中插入值

时间:2013-11-07 10:00:52

标签: sql

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))))))
)

但是这给了我错误。

2 个答案:

答案 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)

  • 每个选择,插入,更新或删除都是一个单独的声明。
  • 所以每个人都需要CTE 表达。
  • 只有第一个人拥有它。