DECLARE @dbName NVARCHAR(255);

DECLARE db_cursor CURSOR FOR
SELECT name 
FROM sys.databases 
WHERE state_desc = 'ONLINE' 
AND is_read_only = 0 
AND source_database_id IS NULL
AND [database_id]>4 --ignore system dbs
AND [is_query_store_on] = 0
;

OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @dbName;

WHILE @@FETCH_STATUS = 0
BEGIN
    EXEC('ALTER DATABASE [' + @dbName + '] SET QUERY_STORE = ON (OPERATION_MODE = READ_WRITE);');
    PRINT 'ALTER DATABASE [' + @dbName + '] SET QUERY_STORE = ON (OPERATION_MODE = READ_WRITE);'
    FETCH NEXT FROM db_cursor INTO @dbName;
END

CLOSE db_cursor;
DEALLOCATE db_cursor;
