简体   繁体   中英

SQL Return subquery 'Total Records' to outer query

This one has me a little stumped, I'm trying to get the total count in my top (root) node XML from this SQL query:

    SELECT COUNT(*) OVER() as '@totalCount', (
        SELECT COUNT(*) OVER() as totalCount, [Title], [Year], [Type], [Poster]
        FROM movies As result where CONTAINS(Title, @Title) Order by [Weight] DESC
        OFFSET ((@PageNumber - 1) * @RowspPage) ROWS
        FETCH NEXT @RowspPage ROWS ONLY
        FOR XML AUTO, type
    ) 
    FOR XML PATH('root')

Obviously the COUNT(*) OVER() is only returning "1" because it's being executed at the top level and not within the subquery. But I only want to display it once in the root node and not repeat per each result.

代码的结果

Any help would be greatly appreciated.

EDIT: Here a working example with common data to walk along:

;with myCTE as
(
    select *
    from sys.objects
)
select (select count(*) from myCTE) as [@Counter]
    ,(
       SELECT myCTE.object_id AS id
             ,mycte.name AS name 
       from myCTE
       for xml path('object'),TYPE
      )       
for xml path('test')

You might try to shift your query into a CTE and put it to something like this:

;WITH MyQueryAsCTE AS
(
    SELECT [Title], [Year], [Type], [Poster]
    FROM movies As result where CONTAINS(Title, @Title) Order by [Weight] DESC
    OFFSET ((@PageNumber - 1) * @RowspPage) ROWS
    FETCH NEXT @RowspPage ROWS ONLY
)
SELECT  (SELECT Count(*) FROM MyQueryAsCTE) as '@totalFound'
       ,[Title] AS [Movie/Title] 
       ,[Year] AS [Movie/Year]
       ,[Type] AS [Movie/Type]
       ,[Poster] AS [Movie/Poster]
FROM MyQueryAsCTE
FOR XML PATH('root')

Fun with strings... This is a total hack, but it works:

DECLARE @totalCount AS INT
DECLARE @result varchar(MAX)

SELECT @totalCount = COUNT(*) OVER(), @result = COALESCE(@result + '', '') + '<result title="' + [Title] + '" year="' + [Year] + '" type="' + [Type] + '"/>'
FROM Movies where CONTAINS(Title, '@Title') Order by [Weight] DESC
OFFSET ((@PageNumber - 1) * @RowspPage) ROWS
FETCH NEXT @RowspPage ROWS ONLY
SELECT '<root totalCount="' + CAST(@totalCount AS VARCHAR) + '">' + @result + '</root>'

Output:

在此输入图像描述

Seems to have a faster/more efficient execution plan as the calculation is only made once and no additional queries to any tables are required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM