Query SQL Server table size and number

-- =================================================== ===================================================== =====
-- Description: Update the size of each table in the query database, and store the results in the data table
-- ========================= ===================================================== ============================
IF EXISTS(SELECT * FROM sysobjects WHERE id = OBJECT_ID('[dbo].[sp_UpdateTableSpaceInfo]' ) AND xtype = 'P')
BEGIN
DROP PROCEDURE [dbo].[sp_UpdateTableSpaceInfo]
END
go
CREATE PROCEDURE [dbo].[sp_UpdateTableSpaceInfo]
AS
BEGIN --Query
whether the result table exists
IF NOT EXISTS (SELECT * FROM sysobjects where id = OBJECT_ID(N'temp_tableSpaceInfo') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
-- create
CREATE TABLE temp_tableSpaceInfo if it does not exist
(name NVARCHAR(128),
rows char(11),
reserved VARCHAR(18),
data VARCHAR(18),
index_size VARCHAR(18),
unused VARCHAR(18))
END
--清空数据表
DELETE FROM temp_tableSpaceInfo

--Define a temporary variable to store the table name during traversal
DECLARE @tablename VARCHAR(255)

--Use the cursor to read all tables table names in the database
DECLARE table_list_cursor CURSOR FOR
SELECT name FROM sysobjects
WHERE OBJECTPROPERTY(id, N'IsTable') = 1 AND name NOT LIKE N'#%%' ORDER BY name

--Open the cursor
OPEN table_list_cursor --Read
the first data
FETCH NEXT FROM table_list_cursor INTO @tablename

-- Traverse the queried table name
WHILE @@FETCH_STATUS = 0
BEGIN
-- Check whether the current table is a user table
IF EXISTS (SELECT * FROM sysobjects WHERE id = OBJECT_ID(@tablename) AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN --The
current table reads its information and inserts it into the table
EXECUTE sp_executesql N'INSERT INTO temp_tableSpaceInfo EXEC sp_spaceused @tbname', N'@tbname varchar(255)', @tbname = @tablename
END --Read
the next A piece of data
FETCH NEXT FROM table_list_cursor INTO @tablename
END

--Release the cursor
CLOSE table_list_cursor
DEALLOCATE table_list_cursor
END

GO

---Specific call method
EXEC sp_UpdateTableSpaceInfo
SELECT * FROM temp_tableSpaceInfo

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325124072&siteId=291194637