我在Sql Server中编写了这样的程序:
CREATE PROCEDURE p_SelectDatesFromRange
(
@startDate DATETIME,
@endDate DATETIME
)
AS
(
;WITH dates AS
(
SELECT @startDate AS [Date]
UNION ALL
SELECT DATEADD(day, 1, [Date])
FROM dates
WHERE [Date] <= @endDate - 1
)
SELECT *
FROM dates
);
它应返回两个给定参数之间的所有日期。但是我无法运行它,它给了我一个错误。
Incorrect syntax near ';'
Incorrect syntax near ')'
此错误位于“with”的开头,位于程序代码的末尾。
我正在学习CTE,很抱歉,如果这是明显的错误。
请帮助,谢谢,迈克。
答案 0 :(得分:2)
我不确定您的错误与CTE本身有什么关系,而是您尝试使用括号来表示存储过程的主体。要么删除括号,要么使用BEGIN
和END
块:
CREATE PROCEDURE p_SelectDatesFromRange
(
@startDate DATETIME,
@endDate DATETIME
)
AS
BEGIN
;WITH dates AS
(
SELECT @startDate AS [Date]
UNION ALL
SELECT DATEADD(day, 1, [Date])
FROM dates
WHERE [Date] <= @endDate - 1
)
SELECT *
FROM dates
END;
答案 1 :(得分:0)
这有效
CREATE PROCEDURE DBO.DateRange
@start datetime,
@end datetime
AS
with cte as
( SELECT @start as strtDt, @end as endDt
union all
select strtDt + 1, endDt
from cte
where strtDt < endDt
)
select * from cte