微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

获取某命名规则下一系列表的总条数

sqlServer(T-sql):

-- 获取某命名规则下的

--
场景:有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




显示结果如下:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐