遍历一个数据库中的所有具有XX_aa_bb格式的表

Aaron_yx 2013-04-09 10:43:40
如题,请各位帮忙看下,我要查询一个数据库(TFDB)中所有的表名为XX_aa_bb格式的表,这些表的列名相同,并且查出所有这些表的sum(sl),sum(je)
在此先谢谢各位了
...全文
223 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
chuifengde 2013-04-09
  • 打赏
  • 举报
回复
引用 6 楼 fa_ge 的回复:
引用 5 楼 chuifengde 的回复:SQL code ? 12 sp_msforeachtable 'SELECT ''?'' TBNAME,SUM(SL) SL,SUM(JE) JE FROM ?',@whereand=' and NAME LIKE ''%#_aa#_bb'' ESCAPE ''#'''--少了个#号 树上的鸟,不愧……
老鹤(货)啊
中国风 2013-04-09
  • 打赏
  • 举报
回复
引用 7 楼 u010206990 的回复:
引用 3 楼 roy_88 的回复:SQL code?1234567use TFDBgo declare @s varchar(max) select @s=isnull(@s+' union all ','')+'select sum(sl) as sl,sum(je) as je from '+Name from sys.tables where name like……
数据量大时有可能
Aaron_yx 2013-04-09
  • 打赏
  • 举报
回复
引用 3 楼 roy_88 的回复:
SQL code?1234567use TFDBgo declare @s varchar(max) select @s=isnull(@s+' union all ','')+'select sum(sl) as sl,sum(je) as je from '+Name from sys.tables where name like '__[_]aa[_]bb'exe……
执行这语句后10多分钟了还是没反应
fa_ge 2013-04-09
  • 打赏
  • 举报
回复
引用 5 楼 chuifengde 的回复:
SQL code ? 12 sp_msforeachtable 'SELECT ''?'' TBNAME,SUM(SL) SL,SUM(JE) JE FROM ?',@whereand=' and NAME LIKE ''%#_aa#_bb'' ESCAPE ''#'''--少了个#号
树上的鸟,不愧是老鸟呀。
chuifengde 2013-04-09
  • 打赏
  • 举报
回复
sp_msforeachtable 'SELECT ''?'' TBNAME,SUM(SL) SL,SUM(JE) JE FROM ?',@whereand=' and NAME LIKE ''%#_aa#_bb'' ESCAPE ''#'''
--少了个#号
chuifengde 2013-04-09
  • 打赏
  • 举报
回复
sp_msforeachtable 'SELECT ''?'' TBNAME,SUM(SL) SL,SUM(JE) JE FROM ?',@whereand=' and NAME LIKE ''%#_aa_bb'' ESCAPE ''#'''
中国风 2013-04-09
  • 打赏
  • 举报
回复
use TFDB
go

declare @s varchar(max)

select @s=isnull(@s+' union all ','')+'select sum(sl) as sl,sum(je) as je from '+Name from sys.tables  where name like '__[_]aa[_]bb'
exec('select sum(sl) as sl,sum(je) as je from ('+@s+') as a')
Aaron_yx 2013-04-09
  • 打赏
  • 举报
回复
引用 1 楼 szm341 的回复:
写游标循环出表名,然后用exec(@sql)的方法拼接出动态sql执行 将结果插入表变量中
游标不会,在网上找了一些遍历的语句,运行后没有我要的表
szm341 2013-04-09
  • 打赏
  • 举报
回复
写游标循环出表名,然后用exec(@sql)的方法拼接出动态sql执行 将结果插入表变量中

27,580

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧