Created
April 8, 2021 14:04
-
-
Save lafleurh/f811c406e26fb0594ee40403e6d4879b to your computer and use it in GitHub Desktop.
Run a SQL command or script on all databases.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Change this to 1 to also run on system databases. | |
DECLARE @UseSystem bit = 0 | |
-- Change this line for the script to run. | |
DECLARE @SQL NVARCHAR(MAX) = 'SELECT DB_NAME() AS DBName, COUNT(*) AS TableCount FROM sys.tables' | |
DECLARE @DBName NVARCHAR(255) | |
DECLARE csrData CURSOR FOR | |
SELECT name | |
FROM sys.databases | |
WHERE ((@UseSystem = 1) OR name NOT IN ('master', 'tempdb', 'model', 'msdb')) | |
ORDER BY name | |
OPEN csrData | |
FETCH csrData INTO @DBName | |
WHILE (@@FETCH_STATUS = 0) | |
BEGIN | |
DECLARE @DBSQL NVARCHAR(MAX) = 'USE [' + @DBName + '] | |
' + @SQL | |
EXECUTE (@DBSQL) | |
FETCH csrData INTO @DBName | |
END | |
CLOSE csrData | |
DEALLOCATE csrData | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment