如何使用 union all ROWCOUNT_BIG() 值

How to ROWCOUNT_BIG() value with union all

我在 SQL 服务器中有以下查询。如何按以下格式获取先前 select 查询的行数?

示例查询

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

示例输出

如果您使用 CTE,您可以 count 行和 union all 在一起:

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

我想您想查看 select 语句的总计数。你可以这样做。

CREATE TABLE #test (id int)
insert into #test(id)
SELECT 1 

SELECT id from #test
union all
SELECT rowcount_big()

注意:此处,ID将根据数据类型优先级隐式转换为BIGINT数据类型。 Read more

据推测,您在某种应用程序中是运行这个。那么为什么不使用 @@ROWCOUNT 呢?

select id, name
from . . .;

select @@rowcount_big;  -- big if you want a bigint

我认为在同一查询中包含该值没有价值。但是,如果底层查询是聚合查询,则可能有一种使用 GROUPING SETS.

的方法

这里有两种方法。最好使用 CTE 来定义行集,这样进一步的 table 插入不会干扰计数。由于您使用的是 ROWCOUNT_BIG() 这些查询使用 COUNT_BIG() (也是 returns bigint)来计算插入的行数。为了确保总数始终显示为最后一行,'order_num' 列已添加到 SELECT 列表和 ORDER BY 子句中。

drop table if exists #tTest;
go
create table #tTest(
  ID        int not null,
  [Name]    varchar(10) not null);

insert into #tTest values
(115, 'Joe'),
(116, 'Jon'),
(117, 'Ron');

/* better to use a CTE to define the row set */
with t_cte as (
    select * 
    from #tTest)
select 1 as order_num, ID, [Name] 
from t_cte
union all
select 2 as order_num, count_big(*), '' 
from t_cte
order by order_num, ID;

/* 2 separate queries could give inconsistent result if table is inserted into */
select 1 as order_num, ID, [Name] 
from #tTest
union all
select 2 as order_num, count_big(*), '' 
from #tTest
order by order_num, ID;

两者都return

order_num   ID  Name
1           115 Joe
1           116 Jon
1           117 Ron
2           3