SQL Server 得到資料庫中所有表的名稱及資料條數

來源:互聯網
上載者:User

提到單個表的資料條數,大家都會想到 select count(*) from tablename

如果是要得到資料庫中所有表的條數呢?我們來看幾種最常見的方式:

--方法一if exists ( select  *            from    dbo.sysobjects            where   id = object_id(N'[dbo].[TableSpace]')                    and objectproperty(id, N'IsUserTable') = 1 )     drop table [dbo].[TableSpace]gocreate table TableSpace    (      TableName varchar(20) ,      RowsCount char(11) ,      Reserved varchar(18) ,      Data varchar(18) ,      Index_size varchar(18) ,      Unused varchar(18)    )godeclare @sql varchar(500)declare @TableName varchar(20)declare mCursor cursorforselect name from sysobjects where xtype='U'open mCursorfetch NEXT from mCursor into @TableNamewhile @@fetch_status = 0     begin        set @sql = 'insert into TableSpace '        set @sql = @sql + ' exec sp_spaceused ''' + @TableName + ''' '        exec (@sql)        fetch NEXT from mCursor into @TableName    endclose mCursordeallocate mCursorgo--顯示結果select TableName,RowsCount from TableSpace--方法二select  b.name as tablename ,        c.row_count as datacountfrom    sys.indexes a ,        sys.objects b ,        sys.dm_db_partition_stats cwhere   a.[object_id] = b.[object_id]        AND b.[object_id] = c.[object_id]        AND a.index_id = c.index_id        AND a.index_id < 2        AND b.is_ms_shipped = 0 --方法三        select  b.name as tablename ,        a.rowcnt as datacountfrom    sysindexes a ,        sysobjects bwhere   a.id = b.id        and a.indid < 2        and objectproperty(b.id, 'IsMSShipped') = 0         --建議使用後兩種方式,對於SQL SERVER 2005來說,三種方法都好使,如果是其他板本,可以逐一測試一下。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.