我試圖建立一個查詢,把他的輸出放在一個表中。 exec(@inloop_query)不知道以前的聲明表。 (在------------------ 之間的部分是可能的,或者我要嘗試做一些事情,不工作? 請告知。T-SQL查詢出錯exec不在表
(我有錯誤是:必須聲明表變量「@inloop_table」嚴重性15國2)
DECLARE @frame_db_name VARCHAR(max)
DECLARE @frame_db_id INT
DECLARE @frame_table TABLE (
db_id INT ,
names VARCHAR(max))
DECLARE @frame_count INT
DECLARE @frame_count_max INT
SET @frame_count = 1
SET @frame_count_max = 0
SELECT @frame_count_max = count (name) FROM sys.databases WHERE Name LIKE 'B%' and state_desc = 'online'
INSERT INTO @frame_table SELECT database_id , name FROM sys.databases WHERE Name LIKE 'B%' and state_desc = 'online' ORDER BY database_id
DECLARE @inloop_query VARCHAR(max)
DECLARE @Inloop_table TABLE (
IL_SchemaName VARCHAR(max) ,
IL_TableName VARCHAR(max) ,
IL_IndexName VARCHAR(max) ,
IL_IndexID INT ,
IL_Fragment INT)
IF @frame_count_max <= 0
PRINT '@count_max (<=0) = ' + CAST(@frame_count_max AS VARCHAR)
ELSE
WHILE @frame_count <= @frame_count_max
BEGIN
SELECT @frame_db_name = names , @frame_db_id = db_id FROM @frame_table WHERE db_id IN (SELECT TOP 1 db_id FROM @frame_table ORDER BY db_id)
PRINT '@count_max (>=0) = ' + CAST(@frame_count_max AS VARCHAR)
PRINT '@count = ' + CAST(@frame_count AS VARCHAR(max))
PRINT 'current DB name = ' + CAST(@frame_db_name AS VARCHAR(max))
PRINT 'current DB ID = ' + CAST(@frame_db_id AS VARCHAR(max))
------------------------------------------------------------
SET @inloop_query = '
USE ' + CAST(@frame_db_name AS VARCHAR(max)) +
' INSERT INTO @inloop_table
SELECT SCHEMA_NAME(o.schema_id) AS SchemaName,
OBJECT_NAME(a.object_id) AS TableName,
i.name AS IndexName,
a.index_id AS IndexID,
convert(tinyint,a.avg_fragmentation_in_percent) AS [Fragment]
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL,NULL, ''LIMITED'') AS a
INNER JOIN sys.indexes i ON i.index_id = a.index_id
AND i.object_id = a.object_id
INNER JOIN sys.objects o ON a.object_id = o.object_id
ORDER BY SchemaName, TableName, IndexID'
EXEC(@inloop_query)
------------------------------------------------------------
SET @frame_count = @frame_count + 1
DELETE FROM @frame_table WHERE db_id IN (SELECT TOP 1 db_id FROM @frame_table ORDER BY db_id)
END
感謝您的支持。 我也想到了這一點,但問題是我不能在我正在處理的數據庫上創建任何表格。 另外我已經嘗試過(並且確實有效)在@inloop_query中創建TABLE,但是我需要在另一次輸出。 我真的希望有一種方法可以使這個工作。 – hexedecimal
那麼GarethD的解決方案呢? –