Advertisement
brunobola

Untitled

Jul 11th, 2024
453
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.17 KB | None | 0 0
  1. DECLARE @dbName NVARCHAR(255)
  2. DECLARE @sqlCommand NVARCHAR(MAX)
  3.  
  4. -- Cursor to iterate over each user database
  5. DECLARE db_cursor CURSOR FOR
  6. SELECT name
  7. FROM sys.databases
  8. WHERE state_desc = 'ONLINE'
  9. AND name NOT IN ('master', 'tempdb', 'model', 'msdb')
  10. AND name NOT LIKE 'PRIEMPRE%'
  11. AND name LIKE 'PRI%'
  12. -- Exclude system databases
  13.  
  14. OPEN db_cursor
  15. FETCH NEXT FROM db_cursor INTO @dbName
  16.  
  17. WHILE @@FETCH_STATUS = 0
  18. BEGIN
  19.     SET @sqlCommand = '
  20.    IF EXISTS (
  21.        SELECT 1
  22.        FROM ' + QUOTENAME(@dbName) + '.sys.tables AS t
  23.        INNER JOIN ' + QUOTENAME(@dbName) + '.sys.schemas AS s
  24.            ON t.schema_id = s.schema_id
  25.        WHERE t.name = ''Movimentos''
  26.          AND s.name = ''dbo''
  27.    )
  28.    BEGIN
  29.        USE ' + QUOTENAME(@dbName) + ';
  30.        CREATE NONCLUSTERED INDEX IX_Movimentos_Utilizador
  31.        ON dbo.Movimentos (DataGravacao)
  32.        INCLUDE (Utilizador);
  33.    END'
  34.    
  35.     -- Print the command for debugging purposes (optional)
  36.     --PRINT @sqlCommand
  37.  
  38.     -- Execute the dynamic SQL command
  39.     EXEC sp_executesql @sqlCommand
  40.    
  41.     FETCH NEXT FROM db_cursor INTO @dbName
  42. END
  43.  
  44. CLOSE db_cursor
  45. DEALLOCATE db_cursor
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement