如何显示具有特定记录数的所有表

时间:2010-11-16 18:14:10

标签: sql sql-server sql-server-2008

有没有办法显示所有具有特定记录数的表?

4 个答案:

答案 0 :(得分:2)

接近100%的准确度:

select object_schema_name(object_id) as schema_name, 
    object_name(object_id) as object_name,
    sum(p.rows)
from sys.partitions p
where index_id in (1,0)
group by object_id
having sum(p.rows) = @numberOfRows;

要获得真正的100%准确度,您必须COUNT(*)来自光标

答案 1 :(得分:1)

This post有一个很好的查询(以及列数和行数):

USE DatabaseName
GO

CREATE TABLE #temp (
       table_name sysname ,
       row_count INT,
       reserved_size VARCHAR(50),
       data_size VARCHAR(50),
       index_size VARCHAR(50),
       unused_size VARCHAR(50))

SET NOCOUNT ON

INSERT #temp
EXEC sp_msforeachtable 'sp_spaceused ''?'''

SELECT a.table_name,
       a.row_count,
       COUNT(*) AS col_count,
       a.data_size
FROM #temp a
INNER JOIN information_schema.columns b
      ON a.table_name collate database_default = b.table_name collate database_default
GROUP BY a.table_name, a.row_count, a.data_size
ORDER BY CAST(REPLACE(a.data_size, ' KB', '') AS integer) DESC

DROP TABLE #temp

答案 2 :(得分:1)

快速而肮脏的方式:

sp_MSForeachtable 'select ''?'' tblName, count(*) from ? where count(*) = X'

这应该只输出那些带有X记录的行

答案 3 :(得分:1)

来自游标的COUNT:

Declare @NumberOfRecords Integer
Set @NumberOfRecords = 100

Create Table #Tables(TableName SysName)
Declare @More Bit
Declare CTable Cursor Local Fast_Forward For Select Table_Name From Information_Schema.Tables Where Table_Type = 'Base Table'
Declare @CTableName SysName
Declare @SQL National Character Varying(4000)

Set @More = 1
Open CTable

While (@More = 1)
Begin
  Fetch Next From CTable Into @CTableName
  If (@@Fetch_Status != 0)
    Set @More = 0
  Else
  Begin
    Set @SQL = N'If (Select Count(*) From [' + @CTableName + ']) = ' + Cast(@NumberOfRecords As National Character Varying) + N' ' +
               N'Insert Into #Tables(TableName) Values(''' + @CTableName + N''')'
    Execute (@SQL)
  End
End

Close CTable
Deallocate CTable

Select * From #Tables
Drop Table #Tables