If you have to monitor a lot of databases for querystore and automatic tuning the code below may help. It checks all the databases and return a list with the database that worth attention (query store off/readonly and automatic tuning off). Works on SQLServer 2017+
drop table if exists #t
SELECT
name,
is_query_store_on,
CAST(NULL AS nvarchar(255)) AS desired_state_desc,
CAST(NULL AS nvarchar(255)) AS actual_state_desc,
CAST(NULL AS nvarchar(255)) AS readonly_reason,
CAST(NULL AS nvarchar(255)) AS autotuning_desired_state_desc,
CAST(NULL AS nvarchar(255)) AS autotuning_actual_state_desc,
CAST(NULL AS INT) AS current_storage_size_mb,
CAST(NULL AS nvarchar(255)) AS command
INTO #t
FROM sys.databases
where
database_id>4; -- only user databases
EXEC sp_MSforeachdb N'USE [?];
UPDATE t SET
desired_state_desc = qs.desired_state_desc,
actual_state_desc = qs.actual_state_desc,
readonly_reason = qs.readonly_reason,
current_storage_size_mb = qs.current_storage_size_mb
FROM #t AS t
CROSS APPLY sys.database_query_store_options AS qs
WHERE
t.is_query_store_on=1
AND t.name=''?'';
UPDATE t SET
autotuning_desired_state_desc = at.desired_state_desc,
autotuning_actual_state_desc = at.actual_state_desc
FROM #t AS t
CROSS APPLY sys.database_automatic_tuning_options AS at
WHERE
t.is_query_store_on=1
AND t.name=''?'';
UPDATE #t set command = ''ALTER DATABASE [?] SET QUERY_STORE = ON;''
WHERE
name =''?''
AND (
is_query_store_on=0
OR actual_state_desc<>desired_state_desc
)
UPDATE #t set command = ''ALTER DATABASE [?] SET AUTOMATIC_TUNING(FORCE_LAST_GOOD_PLAN=ON);''
WHERE
name =''?''
AND (
is_query_store_on=1
AND autotuning_desired_state_desc<>autotuning_actual_state_desc
)
';
select * from #t
where command is not null
order by name asc