在Sql Server 2005中,如何写存储过程,得到数据库中各个表的记录数?

如题所述

给你一个思路:
1:先查询数据库中有多少表放到一张表中
select indentity(int,1,1)name
into #a
from sysobjects where xtype='U'
2:
统计一共有多少张表,循环执行取得每张表的名字,
来查询表的记录数放到一张表b中
3:
查询存放记录的表

你先自己动手写写看,不会的话我在帮你写追问

我参照网络资料写了个存储过程,怎么加入条件判断,比如name like '%公司%'???我贴我的存储过程

set nocount on
if object_id(N'tempdb.db.#temp') is not null
drop table #temp
create table #temp (name sysname,count numeric(18))
insert into #temp
select o.name,i.rows
from sysobjects o,sysindexes i
where o.id=i.id and o.Xtype='U' and i.indid<2
select * from #temp
set nocount off

追答

1:首先创建两张表
--create table FFF1 (id int)
--create table FFF_SUM(name2 char(50),id int)
2:创建存储过程
create proc tFFF_SUM
As
select identity(int,1,1)as id ,name as name1
into #a
from sysobjects where xtype='U' --把

查询的表放到临时表中
declare @total int,@i int,@count Int,@name char(50),@aa varchar(200) --定义一些变量
set @i=1
select @total=count(*) from #a --获得总表数
while @i<@total+1 --循环次数
begin
delete from FFF1 --清空上次的比数
select @name=name1 from #a where id=@i --循环得到表的名字
set @aa='select count(*) from ' +QUOTENAME(@name) --动态执行语句

insert into FFF1
exec(@aa) --把表的记录数方法哦表FFF1中
set @i=@i+1
select @count=id from FFF1 --把数量赋值给变量@count
inSERT INTO FFF_SUM
select @name,@count -- 把表名和记录数放到表FFF_SUM 中
end
--select *from FFF_SUM 存储过程执行完 查询每张表的情况
--最好先用用户表少的数据库来测试

温馨提示:内容为网友见解,仅供参考
第1个回答  2012-10-27
一种很高效的方法:
select SCHEMA_NAME(t.schema_id) + '.' + t.name as tablename,i.rowcnt
from sysindexes as i , sys.tables as t
where i.id = t.object_id and i.indid in (0,1);
第2个回答  2012-10-26
获取表名,循环读取
相似回答
大家正在搜