多个CTE查询,将单个列值分配给局部变量

时间:2019-02-13 16:54:33

标签: sql sql-server-2012 common-table-expression

这是我的SQL查询。如何将Count_CTE.TotalRecords结果分配给本地分配的变量?任何人都可以吗?

DECLARE  @Totalrecords Bigint =0;

;WITH Main_Query_CTE AS(

SELECT 
U.Id,
U.Username,
P.Id as ProfileId,
P.Firstname,
P.Lastname 
FROM   [Dbo].[User] U
INNER JOIN [Profile] P
ON U.Id = P.Userid 
WHERE  AND U.[Status] <>0

),
Count_CTE AS ( SELECT COUNT(*) as TotalRecords FROM Main_Query_CTE )

SELECT * FROM Main_Query_CTE ,Count_CTE
ORDER BY Main_Query_CTE.Id
OFFSET 0 ROWS
FETCH NEXT 20 ROWS ONLY

1 个答案:

答案 0 :(得分:0)

正如Gordan所说,您不能分配变量并在同一选择语句中返回选择。如果需要分配局部变量,最好的选择是将数据放入临时表中,然后从中进行选择。不过,您的问题尚不清楚-不确定您选择的最终目标是什么。

DECLARE  @Totalrecords Bigint =0;

SELECT 
U.Id,
U.Username,
P.Id as ProfileId,
P.Firstname,
P.Lastname 
into #temp
FROM   [Dbo].[User] U
INNER JOIN [Profile] P
ON U.Id = P.Userid 
WHERE  AND U.[Status] <> 0  

select @Totalrecords = COALESCE(COUNT(*),0) FROM #temp;

SELECT *
FROM #temp
ORDER BY id
OFFSET 0 ROWS
FETCH NEXT 20 ROWS ONLY