2016-11-14 18 views
2

我想調用sp_spaceused來獲取我想監視的幾個特定表中的行數,但我試圖避免使用遊標。如何在特定表上使用sp_spaceused?

我做了一個表來保存所有我要監控的表:

CREATE TABLE MonitoredTable 
(
    MonitoredTableID INT PRIMARY KEY IDENTITY(1, 1) NOT NULL 
    , DatabaseName NVARCHAR(128) NOT NULL 
    , SchemaName NVARCHAR(128) NOT NULL 
    , TableName NVARCHAR(128) NOT NULL 
    , RowNumberThreshold INT NOT NULL 
    , IsActive BIT NOT NULL 
) 

我的問題是:我想創建一個函數,將只爲表自己的行數返回MonitoredTableID小號超過定義的RowNumberThreshold

這是我想要做的,什麼,但,這是無效的SQL

CREATE FUNCTION dbo.GetTablesLargerThanThreshold() 
RETURNS @tablesLargerThanThreshold TABLE 
(
    MonitoredTableID INT NOT NULL 
) 
AS 
BEGIN 
    INSERT INTO @tablesLargerThanThreshold 
    SELECT MonitoredTableID 
    FROM MonitoredTable 
    WHERE IsActive = 1 
     AND (SELECT [rows] FROM (EXEC sp_spaceused DatabaseName + '.' + SchemaName + '.' + TableName)) > RowNumberThreshold 

    RETURN 
END 

有如果rowsMonitoredTable數量比定義RowNumberThreshold更大的一種方法,我可以檢查不訴諸於光標?

回答

1

是這樣的?

-- See the following pages for documentation on the tables used in this query: 
-- 
-- sys.indexes    https://msdn.microsoft.com/en-us/library/ms173760.aspx 
-- sys.partitions   https://msdn.microsoft.com/en-us/library/ms175012.aspx 
-- sys.allocation_units  https://msdn.microsoft.com/en-us/library/ms189792.aspx 
-- sys.tables    Only columns inherited from sys.object, see link below 
-- sys.object    https://msdn.microsoft.com/en-us/library/ms190324.aspx 
SELECT OBJECT_NAME(i.OBJECT_ID) AS [TableName] 
    , p.[rows] AS [Num_Rows] 
FROM sys.indexes AS i 
    INNER JOIN sys.partitions AS p 
     ON p.OBJECT_ID = i.OBJECT_ID 
     AND p.index_id = i.index_id 
    INNER JOIN sys.allocation_units AS a 
     ON a.container_id = p.partition_id 
    INNER JOIN sys.tables AS t 
     ON i.OBJECT_ID = t.OBJECT_ID 
WHERE i.type <= 1 -- Heap or clustered index 
    AND a.type = 1 -- In-row data 
    AND t.type = 'U' -- User-defined table 
    AND t.is_ms_shipped = 0 -- sys.object was not created by an internal SQL Server component 
+0

這比我需要的略多(我只需要sp_spaceused存儲過程中的行數)。我編輯了您的答案以匹配我使用的答案。請在您有機會確保我的筆記有意義並且正確使用查詢時快速查看。感謝你的回答!! –

+1

我會在今天晚些時候或明天晚些時候看看。很高興我能幫上忙。 –

相關問題