我是sql的新手,我现在创建了一个CTE,我想从CTE结果集中获取行数
DECLARE @start_date date,@end_date DATE ;
select @start_date= min(ETA) from [dbo].[testTable]
select @end_date=max(ETA) from [dbo].[testTable];
;WITH AllDays
AS (
SELECT @start_date AS [Date]
--, 1 AS [level]
UNION ALL
SELECT DATEADD(DAY, 1, [Date])
--, [level] + 1
FROM AllDays
WHERE [Date] < @end_date )
--Insert into #tempETA (CallETA)
SELECT [Date]--, [level]
FROM AllDays OPTION (MAXRECURSION 0)
select count(a.Date),a.Date from AllDays a
我在这里收到错误:
(1048 row(s) affected)
Msg 208, Level 16, State 1, Line 20
Invalid object name 'AllDays'.
答案 0 :(得分:2)
CTE
可以保存在单个SELECT, INSERT, UPDATE, DELETE
的执行范围内定义的临时结果集。您不能在SELECT
CTE
使用@@ROWCOUNT
获取CTE
的计数。考虑到您需要CTE
结果及其计数。
SELECT [Date]--, [level]
FROM AllDays OPTION (MAXRECURSION 0)
select @@ROWCOUNT
如果您想要计算成为结果的一部分,请使用COUNT() OVER()
SELECT [Date],count(1)over() as Total_count
FROM AllDays OPTION (MAXRECURSION 0)
答案 1 :(得分:1)
查看以下代码并告诉您。这是您想要的。?
DECLARE @start_date date,@end_date DATE ;
select @start_date= min(ETA) from [dbo].[testTable]
select @end_date=max(ETA) from [dbo].[testTable];
;WITH AllDays
AS (
SELECT @start_date AS [Date]
--, 1 AS [level]
UNION ALL
SELECT DATEADD(DAY, 1, @start_date)
--, [level] + 1
FROM [testTable]
WHERE @start_date < @end_date )
--Insert into #tempETA (CallETA)
--SELECT [Date]--, [level]
--FROM AllDays OPTION (MAXRECURSION 0)
select count(a.Date) from AllDays a