Search code examples
sqlsql-servert-sqlcountunion-all

How to ROWCOUNT_BIG() value with union all


I have the following query in SQL Server. How do I get the number of rows of previous select query as following format?

Sample Query

select ID, Name FROM Branch
UNION ALL
SELECT ROWCOUNT_BIG(), ''

Sample Output

Sample Output


Solution

  • If you use a CTE you can count the rows and union all together:

    with cte as (
        select ID, [Name]
        from dbo.Branch
    )
    select ID, [Name]
    from cte
    union all
    select count(*) + 1, ''
    from cte;