Skip to content

Instantly share code, notes, and snippets.

@FlogDonkey
Last active October 27, 2022 16:32
Show Gist options
  • Save FlogDonkey/0cc3e6f7f5720a3161399883e9becab3 to your computer and use it in GitHub Desktop.
Save FlogDonkey/0cc3e6f7f5720a3161399883e9becab3 to your computer and use it in GitHub Desktop.
Enables query store for all user databases on a supported edition of SQL Server (2016 or higher). Much faster than enabling via the GUI one DB at a time.
BEGIN
DECLARE @RowID INT;
DECLARE @Table TABLE
(
RowNum INT IDENTITY(1, 1)
,DBName VARCHAR(100)
,Command1 NVARCHAR(MAX)
,Command2 NVARCHAR(MAX)
);
INSERT INTO @Table
(
DBName
,Command1
,Command2
)
SELECT d.name
,'ALTER DATABASE [' + d.name + '] SET QUERY_STORE = ON'
,'ALTER DATABASE [' + d.name + '] SET QUERY_STORE (OPERATION_MODE = READ_WRITE)'
FROM sys.databases AS d
WHERE 1 = 1
AND d.name NOT IN ('tempdb', 'master')
AND d.is_query_store_on = 0;
SELECT @RowID = @@ROWCOUNT;
WHILE @RowID > 0
BEGIN
DECLARE @WorkingSQL NVARCHAR(MAX);
SELECT @WorkingSQL = t.Command1
FROM @Table AS t
WHERE t.RowNum = @RowID;
EXEC (@WorkingSQL);
SELECT @WorkingSQL = t.Command2
FROM @Table AS t
WHERE t.RowNum = @RowID;
EXEC (@WorkingSQL);
SELECT @RowID = @RowID - 1;
END;
END;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment