查詢sql資料庫中表佔用的空間大小

來源:互聯網
上載者:User

   1.SQL統計資料,大量事務操作後可能不準

  exec sp_spaceused '表名'

  2.準確的資料表空間大小,但可能會花些統計時間

  exec sp_spaceused '表名', true

  3.資料庫大小查詢

  exec sp_spaceused

  4.所有使用者資料表空間表小,SQL統計資料,,大量事務操作後可能不準

  exec sp_MSforeachtable "exec sp_spaceused '?'"

  5. 所有使用者資料表空間表小,大資料庫慎用

  exec sp_MSforeachtable "exec sp_spaceused '?',true"

  create table #t(

  name varchar(200),

  rows int,

  reserved varchar(25),

  data varchar(25),

  index_size varchar(25),

  unused varchar(25))

  exec sp_MSforeachtable "insert into #t exec sp_spaceused '?'"

  select TOP 100 * from #t ORDER BY rows DESC

  drop table #t

  sp_MSforeachtable使用方法

  1)說明

  系統預存程序sp_MSforeachtable和sp_MSforeachdb,是微軟提供的兩個不公開的預存程序,從ms sql 6.5開始。

  存放在SQL Server的MASTER資料庫中。

  2)參數說明:

  @command1 nvarchar(2000), --第一條啟動並執行SQL指令

  @replacechar nchar(1) = N'?', --指定的預留位置號

  @command2 nvarchar(2000)= null, --第二條啟動並執行SQL指令

  @command3 nvarchar(2000)= null, --第三條啟動並執行SQL指令

  @whereand nvarchar(2000)= null, --可選條件來選擇表

  @precommand nvarchar(2000)= null, --執行指令前的操作(類似控制項的觸發前的操作)

  @postcommand nvarchar(2000)= null --執行指令後的操作(類似控制項的觸發後的操作)

  3)舉例

  --統計資料庫裡每個表的詳細情況

  exec sp_MSforeachtable @command1="sp_spaceused '?'"

  --獲得每個表的記錄數和容量:

  EXEC sp_MSforeachtable @command1="print '?'",

  @command2="sp_spaceused '?'",

  @command3= "SELECT count(*) FROM ? "

  --獲得所有的資料庫的儲存空間:

  EXEC sp_MSforeachdb @command1="print '?'",

  @command2="sp_spaceused "

  --檢查所有的資料庫

  EXEC sp_MSforeachdb @command1="print '?'",

  @command2="DBCC CHECKDB (?) "

  --更新PUBS資料庫中已t開頭的所有表的統計:

  EXEC sp_MSforeachtable @whereand="and name like 't%'",

  @replacechar='*',

  @precommand="print 'Updating Statistics.....' print ''",

  @command1="print '*' update statistics * ",

  @postcommand= "print''print 'Complete Update Statistics!'"

  --刪除當前資料庫所有表中的資料

  sp_MSforeachtable @command1='Delete from ?'

  sp_MSforeachtable @command1 = "TRUNCATE TABLE ?"

  4)參數@whereand的用法

  @whereand參數在預存程序中起到指令條件限制的作用,具體的寫法如下:

  @whereend,可以這麼寫 @whereand=' AND o.name in (''Table1'',''Table2'',.......)'

  例如:我想更新Table1/Table2/Table3中NOTE列為NULL的值

  sp_MSforeachtable @command1='Update ? Set NOTE='''' Where NOTE is NULL',@whereand=' AND o.name in (''Table1'',''Table2'',''Table3'')'

  5)"?"在預存程序的特殊用法,造就了這兩個功能強大的預存程序

  這裡"?"的作用,相當於DOS命令中、以及我們在WINDOWS下搜尋檔案時的萬用字元的作用。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.