我正在尝试使用公共表表达式来获取记录和记录计数,但我想将记录计数存储在变量中,并且它会导致错误
为变量赋值的SELECT语句不能是 结合数据检索操作。
我正在尝试这样的事情
declare @count int
;with allRecords as
(
-- query fetching all the records with many joins
),
recordsCount as
(
select count(*) as Total from allRecords
)
select allRecords.*, @count=recordsCount.Total from allRecords, recordsCount
where -- multiple conditions
这有什么工作吗?
实际上@count
变量是我的存储过程的output
变量,因此我想返回结果并填充此@count
变量
答案 0 :(得分:1)
你不能这样做。如果要获取select语句返回到变量的行数,则应使用内置全局变量@@ROWCOUNT
:
DECLARE @count int
;WITH allRecords as
(
-- query fetching all the records with many joins
)
SELECT allRecords.*
FROM allRecords
SELECT @Count = @@ROWCOUNT
<强>更新强>
那么,在这种情况下,你没有选择我知道的其他选择然后使用临时表:
SELECT /* columns */ INTO #tempTableName
-- rest of the select statement
SELECT @Count = COUNT(*)
FROM #tempTableName
SELECT *
FROM #tempTableName
WHERE <conditions>
DROP TABLE #tempTableName
答案 1 :(得分:0)
declare @count int
;with allRecords as
(
-- query fetching all the records with many joins
)
select @count = count(*) as Total from allRecords
答案 2 :(得分:0)
我在这里使用临时表或表变量。然后,您可以针对select @count = count(*) from #allrecords
和select * from #allrecords