Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

result of code

Any help would be greatly appreciated.

like image 793
bfritz Avatar asked Sep 04 '26 22:09

bfritz


1 Answers

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')
like image 174
Shnugo Avatar answered Sep 07 '26 11:09

Shnugo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!