日期:2014-05-18  浏览次数:20520 次

如何計算出每個表的記錄數?
現有一表A,計錄了數據據中各表的表名
我現在想得到每個表的記錄數
我想這樣寫,可是不行,請高手指點下

Select   A.TableName,記錄數=(Select   count(*)   from   a.TableName)
From   A

------解决方案--------------------
select tablename,cou=(select count(1) from a where tablename=b.tablename)
from a b
------解决方案--------------------
select 'select TableName= ' ' ' + TableName + ' ' ', 记录数=count(*) from ' + TableName from A
--把结果集粘贴出来运行
------解决方案--------------------
declare @sql varchar(1000)
set @sql= 'Select A.TableName,記錄數=(Select count(*) from ( '+select a.tablename from a) t+ ') From A '

------解决方案--------------------
用存储过程 然后拼成字符串执行
------解决方案--------------------

--one: 使用系统表.
SELECT object_name (i.id) TableName, rows as RowCnt
FROM sysindexes i INNER JOIN sysObjects o ON (o.id = i.id AND o.xType = 'U ')
WHERE indid < 2
ORDER BY TableName

--******************

--two: 使用未公开的过程 "sp_MSforeachtable "
CREATE TABLE #temp (TableName VARCHAR (255), RowCnt INT)
EXEC sp_MSforeachtable 'INSERT INTO #temp SELECT ' '? ' ', COUNT(*) FROM ? '
SELECT TableName, RowCnt FROM #temp ORDER BY TableName
DROP TABLE #temp

--******************

-- three: 使用游标.cursor
SET NOCOUNT ON
DECLARE @tableName VARCHAR (255), @sql VARCHAR (300)
CREATE TABLE #temp (TableName VARCHAR (255), rowCnt INT)
DECLARE myCursor CURSOR FAST_FORWARD READ_ONLY FOR
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'base table '
OPEN myCursor
FETCH NEXT FROM myCursor INTO @tableName
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC ( 'INSERT INTO #temp (TableName, rowCnt) SELECT ' ' ' + @tableName + ' ' ' as tableName, count(*) as rowCnt from ' + @tableName)
FETCH NEXT FROM myCursor INTO @tableName
END
SELECT TableName, RowCnt FROM #temp ORDER BY TableName
CLOSE myCursor
DEALLOCATE myCursor
DROP TABLE #temp

------解决方案--------------------
SQLSERVER中统计所有表的记录数:
http://blog.csdn.net/minisunny/archive/2007/09/19/1791760.aspx

------解决方案--------------------
exec sp_MSforeachtable 'SELECT ' '? ' ' as tablename,count(*) as count FROM ? '
------解决方案--------------------
汗!!!!!!!!!
------解决方案--------------------
select count(*) from 表名
------解决方案--------------------
study
------解决方案--------------------
mark 一下
------解决方案--------------------
select count(*) as '表记录总数 ' from tablename
就ok了啊
------解决方案--------------------
gdgdgdgsgdgsdgsdg
------解决方案--------------------
select TableName,count(*) From A Group by TableName
------解决方案--------------------
对了,要拼字符串,变量不能作为表名和字段名.