-
MelissaMa-MSFT 24,136 Reputation points
2021-09-24T05:48:35.223+00:00 Hi @RuoRuo ,
Is it possible to query all DBs in the server and put these dbs in the Alter View command automatically?
Please refer below and check whether it is helpful.
declare @sql nvarchar(max)='' set @sql = N' ALTER VIEW [dbo].[DBHISTVIEW] as ( select * from (' SELECT @sql =@sql+ STUFF(( SELECT ' (select * from ' + QUOTENAME(NAME)+'.[dbo].[DBHIST]) union all ' FROM sys.databases WHERE database_id > 4 --exclude all system database and NAME like 'db_20%' --filter all database start with db_20. FOR XML PATH('') ), 1, 1, '') SET @sql=SUBSTRING(@SQL,1,LEN(@SQL)-LEN('union all'))+ ') as x)' --print @sql EXEC(@sql)
Best regards,
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Hi @RuoRuo ,
Welcome to Microsoft Q&A!
I changed the name of your view from '[dbo].[DBHIST]' to '[dbo].[DBHISTVIEW]' due to the error 'There is already an object named 'DBHIST' in the database.' reported when I created your view.
Please refer below and check whether it is working.
DECLARE @DBNAME DATE=DATEADD(MONTH,-11,getdate())
declare @sql nvarchar(max)=''
set @sql = N' ALTER VIEW [dbo].[DBHISTVIEW] as (
select * from ('
WHILE @DBNAME<=CAST(getdate() AS DATE)
BEGIN
SET @sql=@sql+' (select * from [DB_'+FORMAT(@DBNAME,'yyyyMM')+'].[dbo].[DBHIST]) union all'
SET @DBNAME=DATEADD(MONTH,1,@DBNAME)
END
SET @sql=SUBSTRING(@SQL,1,LEN(@SQL)-LEN('union all'))+ ') as x)'
--print @sql
EXEC(@sql)
Best regards,
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.