查詢某個資料庫、以及其中每個資料表佔據的儲存空間大小,包括索引佔的空間大小:
if not exists
(
select * from dbo.sysobjects
where id = object_id(N'[dbo].[tablespaceinfo]')
and OBJECTPROPERTY(id, N'IsUserTable') = 1
)
create table tablespaceinfo
(
nameinfo varchar(50) ,
rowsinfo int , reserved varchar(20) ,
datainfo varchar(20) ,
index_size varchar(20) ,
unused varchar(20)
)
delete from tablespaceinfo --清空原有資料表
declare @tablename varchar(255)
declare @cmdsql varchar(500)
DECLARE Info_cursor CURSOR FOR
select o.name
from dbo.sysobjects o where OBJECTPROPERTY(o.id, N'IsTable') = 1
and o.name not like N'#%%' order by o.name
OPEN Info_cursor
FETCH NEXT FROM Info_cursor
INTO @tablename
WHILE @@FETCH_STATUS = 0
BEGIN
if exists
(
select * from dbo.sysobjects
where id = object_id(@tablename) and OBJECTPROPERTY(id, N'IsUserTable') = 1
)
execute sp_executesql
N'insert into tablespaceinfo exec sp_spaceused @tbname',
N'@tbname varchar(255)',
@tbname = @tablename
FETCH NEXT FROM Info_cursor
INTO @tablename
END
CLOSE Info_cursor --閉關遊標
DEALLOCATE Info_cursor --釋放遊標
GO
sp_spaceused @updateusage = 'TRUE'
select * from tablespaceinfo
order by cast(left(ltrim(rtrim(reserved)) , len(ltrim(rtrim(reserved)))-2) as int) desc
查詢所有資料庫的恢復模式(Simple/Full),以及每個資料庫的檔名、物理路徑、儲存空間、可用空間:
SELECT [name], recovery_model_desc, log_reuse_wait_desc FROM sys.databases;
SELECT name AS [File Name], file_id,
physical_name AS [Physical Name],
size/128 AS [Total Size in MB],
size/128.0 - CAST(FILEPROPERTY(name,'SpaceUsed') AS int)/128.0AS [Available Space In MB]
FROM sys.database_files;
利用上面的方法找到log檔名以後,清楚log檔案
dbcc shrinkfile( log檔名 , 1)