Source: Use a T-SQL statement to bulk query the data table footprint and its number of rows
The amount of space that the data table occupies and the number of rows that exist in the database to find. You can use sp_spaceused to match the name of the datasheet. You can generate the amount of space that the table consumes and the number of existing rows.
Such as:
Use ADVENTUREWORKS
GO
EXEC sp_spaceused [Sales.SalesOrderHeader]
GO
But how can a SQL statement be implemented if the database contains thousands of of the data tables?
Workaround:
First, dynamic sql:
The expression is generated dynamically in T-SQL and then executed in a query. Such as:
Use ADVENTUREWORKS
GO
SET NOCOUNT on
SELECT ' EXEC sp_spaceused ['+S. name + '. ' + T . name + ']; '
from SYS . Tables T INNER JOIN sys. Schemas S
on T . schema_id = S . schema_id
WHERE S . NAME = ' HumanResources '
SET NOCOUNT OFF
The results are as follows:
Copy the results to a new window to execute to get the results.
But this method requires manual operation which is not suitable for automatic and timed operation.
Second, the dynamic generation using the method of accumulating string:
Because it is automated, a dynamic expression is executed using the INSERT trigger of the data table. and automatically will input the data table, calculate the result:
-- Create a table, execute Insert Trigger
Use AdventureWorks
GO
CREATE TABLE Mytab
(
TableName VARCHAR (255)
)
GO
-- To create a trigger:
CREATE TRIGGER TR2 on Mytab
After INSERT
as
DECLARE @sql VARCHAR (max)
SET @sql = "'
-- use an additive string to produce a statement
SELECT @sql = @sql +
' EXEC sp_spaceused ['+TableName+']; '
from inserted
-- Use EXECUTE Executing dynamic statements
EXEC (@sql)
-- adds the specified data table name and automatically displays the data table's usage space:
INSERT Mytab
SELECT S . name + '. ' + T . name
from SYS . Tables T INNER JOIN sys. Schemas S
on T . schema_id = S . schema_id
WHERE S . name = ' HumanResources '
Bulk query of data table footprint and its rows using a T-SQL statement