--获取某命名规则下的
--场景:有1000个后缀逐渐递增的表(如果是上万了也可做相应的改动实现),获取这些表总的数据条数
--表的形式:tb_user000,tb_user001,tb_user010,tb_user011,tb_user999
--命名规则:000,001...009,010,011..999
declare @i int --表开始后缀
declare @str nvarchar(1000) --执行语句
declare @tab varchar(100) --表前缀
declare @tab_suffix varchar(10) --表后缀
declare @max int --表个数
set @i=0
set @tab='tb_user'
set @max=1000
if exists(select * from tempdb.dbo.sysobjects where id=OBJECT_ID('tempdb..#t1') and xtype='U')
drop table #t1
create table #t1(id int identity(1,1),num int,tab varchar(100))
while @i<@max
begin
if @i>=0 and @i<10
set @tab_suffix='00'
else if @i>9 and @i<100
set @tab_suffix='0'
else if @i>99 and @i<1000
set @tab_suffix=''
set @str=N' insert into #t1(num,tab) select Total,'''+@tab+@tab_suffix+cast(@i as varchar)+''' from
(select Total = count(*) from '+@tab+@tab_suffix+cast(@i as varchar)+') a'
print @str;
exec sp_executesql @str;
set @i=@i+1;
end
select num,tab,sum_num from (
select sum(num) as sum_num from #t1) b,#t1
--场景:有1000个后缀逐渐递增的表(如果是上万了也可做相应的改动实现),获取这些表总的数据条数
--表的形式:tb_user000,tb_user001,tb_user010,tb_user011,tb_user999
--命名规则:000,001...009,010,011..999
declare @i int --表开始后缀
declare @str nvarchar(1000) --执行语句
declare @tab varchar(100) --表前缀
declare @tab_suffix varchar(10) --表后缀
declare @max int --表个数
set @i=0
set @tab='tb_user'
set @max=1000
if exists(select * from tempdb.dbo.sysobjects where id=OBJECT_ID('tempdb..#t1') and xtype='U')
drop table #t1
create table #t1(id int identity(1,1),num int,tab varchar(100))
while @i<@max
begin
if @i>=0 and @i<10
set @tab_suffix='00'
else if @i>9 and @i<100
set @tab_suffix='0'
else if @i>99 and @i<1000
set @tab_suffix=''
set @str=N' insert into #t1(num,tab) select Total,'''+@tab+@tab_suffix+cast(@i as varchar)+''' from
(select Total = count(*) from '+@tab+@tab_suffix+cast(@i as varchar)+') a'
print @str;
exec sp_executesql @str;
set @i=@i+1;
end
select num,tab,sum_num from (
select sum(num) as sum_num from #t1) b,#t1
显示结果如下: