Site icon Mr. 沙先生

[MSSQL]DB log減肥、資料表佔用空間筆記

由於 DB 內屬重要的資料,但其實也會有系統將暫存資料寫在 DB 內造成資料成長很快,DB 資料庫常有越來越肥大的狀況,這時候就會需要以下方式來讓 DB 減減肥

Log 減肥

EXEC sp_helpdb "DatabaseName"
alter database "DatabaseName" set recovery simple with no_wait
DBCC SHRINKFILE([name],2)
alter database "DatabaseName" set recovery full with no_wait

若是不想儲存交易紀錄,可於資料庫屬性→ 選項→ 復原模式設為”簡單”  

取得資料庫中各 Table 的使用量資訊

SET NOCOUNT ON
DBCC UPDATEUSAGE(0)
EXEC sp_spaceused
CREATE TABLE #t
(
  [name] NVARCHAR(128),
  [rows] CHAR(11),
  reserved VARCHAR(18), 
  data VARCHAR(18), 
  index_size VARCHAR(18),
  unused VARCHAR(18)
)
INSERT #t EXEC sys.sp_MSforeachtable 'EXEC sp_spaceused ''?''' 
SELECT * 
, LTRIM(STR(CAST(LEFT(reserved,LEN(reserved)-3) AS NUMERIC(18,0)) / 1024, 18)) + 'MB'
AS reservedSize_M
, LTRIM(STR(CAST(LEFT(data,LEN(data)-3) AS NUMERIC(18,0)) / 1024, 18)) + 'MB' 
AS dataSize_M
, LTRIM(STR(CAST(LEFT(index_size,LEN(index_size)-3) AS NUMERIC(18,0)) / 1024, 18)) + 'MB'
AS indexSize_M
FROM #t
ORDER BY CAST(LEFT(data,LEN(data)-3) AS NUMERIC(18,0)) DESC
SELECT SUM(CAST([rows] AS int)) AS [rows]
, LTRIM(STR(SUM(CAST(LEFT(reserved,LEN(reserved)-3) AS NUMERIC(18,0))) / 1024, 18)) + 'MB' 
AS sumOfreservedSize_M
, LTRIM(STR(SUM(CAST(LEFT(data,LEN(data)-3) AS NUMERIC(18,0))) / 1024, 18)) + 'MB'
AS sumOfdataSize_M
, LTRIM(STR(SUM(CAST(LEFT(index_size,LEN(index_size)-3) AS NUMERIC(18,0))) / 1024, 18)) + 'MB'
AS sumOfindexSize_M
FROM #t
Exit mobile version