Sql-Server
TSQL 腳本返回錯誤結果
我正在嘗試使用以下程式碼找出所有數據庫中是否存在特定的索引名稱“Test”。對於實例中的所有數據庫,我得到的結果始終是“不存在”。但是,索引確實存在於少數數據庫中。有人可以指出程式碼錯誤的地方嗎?
DECLARE @Name AS VARCHAR(100) DECLARE dbCur CURSOR FOR SELECT name FROM SYS.databases where name not in ('master','msdb','model','tempdb') OPEN dbCur FETCH NEXT FROM dbCur INTO @Name WHILE @@FETCH_STATUS = 0 BEGIN --Check if index exist EXECUTE('USE [' + @Name + ']') If 1 = ((SELECT COUNT(*) as index_count FROM sys.indexes WHERE object_id = OBJECT_ID('dbo.TestTable') AND name = 'Test')) Print 'INDEX EXIST ' + @Name; ELSE Print 'INDEX DOES NOT EXIST ' + @Name; FETCH NEXT FROM dbCur INTO @Name END CLOSE dbCur DEALLOCATE dbCur
結果:
INDEX DOES NOT EXIST DB1 INDEX DOES NOT EXIST DB2 INDEX DOES NOT EXIST DB3 INDEX DOES NOT EXIST DB4
您的問題可能與在游標內發出 USE 有關。相反,我建議使用以下方法,這樣您就可以擺脫游標。
EXEC sp_MSforeachdb 'USE ? IF ''?'' <> ''master'' AND ''?'' <> ''model'' AND ''?'' <> ''msdb'' AND ''?'' <> ''tempdb'' BEGIN IF EXISTS(SELECT 1 FROM sys.indexes ind WHERE object_id = OBJECT_ID(''dbo.TestTable'') AND name = ''Test'') PRINT ''Exists in '' + DB_NAME() ELSE PRINT ''Not Exists in '' + DB_NAME() END'
請注意,從技術上講,sp_MSforeachdb 是一個未記錄的功能,但它可以正常工作。