我在sql server 2008中有一个表,其中列'TableName'表示特定表的名称。
TableName
----------
Person
Good
Organization
我想遍历此表并计算每个表的行数。
答案 0 :(得分:0)
这将为您提供所有表的表名和行数。
方法1:使用系统表 - 提供近似行数
SELECT p.object_id, t.name, sum(p.rows) from sys.partitions p
inner join sys.tables t on p.object_id = t.object_id
group by p.object_id, t.name
order by 1
如果您正在管理自己的表
SELECT p.object_id, t.name, sum(p.rows) from sys.partitions p
inner join sys.tables t on p.object_id = t.object_id
inner join TableName u on u.TableName = t.name
group by p.object_id, t.name
order by 1
方法2:使用游标 - 精确行数
declare @tbl table(table_name varchar(100), rows bigint)
declare @tblName varchar(100) = ''
DECLARE @cur CURSOR
SET @cur = CURSOR FAST_FORWARD
FOR
SELECT TableName FROM YourTable
OPEN @cur
FETCH NEXT FROM @cur
INTO @tblName
WHILE @@FETCH_STATUS = 0
BEGIN
declare @query nvarchar(2000) --Passing parameter into dynamic query
declare @out bigint =0 --Passing out parameter into dynamic query
set @query = N'select @out = count(*) from ' + @tblName
EXECUTE sp_executesql @query, N'@tblName varchar(100), @out bigint output'
, @tblName = @tblName, @out = @out OUTPUT;
INSERT into @tbl (table_name, rows) VALUES(@tblName, @out)
FETCH NEXT FROM @cur
INTO @tblName
END
CLOSE @cur
DEALLOCATE @cur
select * from @tbl
答案 1 :(得分:0)
如果我假设您有一个包含数据库表名的表,则可以查询为。
Select count(*) from (select tablename from tablenames);