DECLARE @dbName NVARCHAR(255);
DECLARE @sql NVARCHAR(MAX);

-- Cursor to iterate through all user databases
DECLARE db_cursor CURSOR FOR
SELECT d.name 
FROM sys.databases d
WHERE [is_query_store_on] = 1  -- Filters databases where Query Store is enabled
AND d.[source_database_id] IS NULL 
;

OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @dbName;

WHILE @@FETCH_STATUS = 0
BEGIN
    SET @sql = 'ALTER DATABASE [' + @dbName + '] SET QUERY_STORE = OFF;';
    PRINT @sql;  -- Optional: to view the SQL commands being executed
    EXEC sp_executesql @sql;

    FETCH NEXT FROM db_cursor INTO @dbName;
END;

CLOSE db_cursor;
DEALLOCATE db_cursor;
