3

此过程是否准确显示数据库中使用的空间?我怀疑结果。

DECLARE @TableName VARCHAR(100)    --For storing values in the cursor

--Cursor to get the name of all user tables from the sysobjects listing
DECLARE tableCursor CURSOR
FOR 
select [name]
from dbo.sysobjects 
where  OBJECTPROPERTY(id, N'IsUserTable') = 1
FOR READ ONLY

--A procedure level temp table to store the results
CREATE TABLE #TempTable
(
    tableName varchar(100),
    numberofRows varchar(100),
    reservedSize varchar(50),
    dataSize varchar(50),
    indexSize varchar(50),
    unusedSize varchar(50)
)

--Open the cursor
OPEN tableCursor

--Get the first table name from the cursor
FETCH NEXT FROM tableCursor INTO @TableName

--Loop until the cursor was not able to fetch
WHILE (@@Fetch_Status >= 0)
BEGIN
    --Dump the results of the sp_spaceused query to the temp table
    INSERT  #TempTable
        EXEC sp_spaceused @TableName

    --Get the next table name
    FETCH NEXT FROM tableCursor INTO @TableName
END

--Get rid of the cursor
CLOSE tableCursor
DEALLOCATE tableCursor

--Select all records so we can use the reults
SELECT * 
FROM #TempTable order BY tablename

--Final cleanup!
DROP TABLE #TempTable

很抱歉这篇文章的格式。StackO 肯定有问题 - 今天没有格式化工具栏。

4

2 回答 2

1

您的代码提供了已用空间的逐表视图。您也可以sp_spaceused不带参数运行以获取整个数据库大小的概览。是什么让你怀疑结果?

于 2012-05-10T15:20:13.953 回答
1

您不妨考虑使用系统的动态视图/功能之一

例如,考虑使用sys.dm_db_index_physical_stats来返回有关用于堆聚集和非聚集索引的页面的更详细信息的简单查询:

select * from sys.dm_db_index_physical_stats ( 
    DEFAULT 
  , DEFAULT 
  , DEFAULT 
  , DEFAULT 
  , 'DETAILED'
)
于 2012-05-10T15:25:20.627 回答