I have hundreds of DB on an instance and I want to remove the DB from their AG (each DB is in a separate AG), remove the listener and then delete that AG. I have written the script below to automate this a bit:
DECLARE @name VARCHAR(50);
DECLARE @sql nvarchar(4000);
DECLARE db_cursor CURSOR FOR select name from sys.sysdatabases where name not in ('testing_db');
Open db_cursor
Fetch Next From db_cursor Into @name
WHILE @@FETCH_STATUS = 0
BEGIN
select @sql =
'ALTER AVAILABILITY GROUP [' + @name + '] REMOVE DATABASE [' + @name + '];' + char(10) +
'ALTER AVAILABILITY GROUP [' + @name + '] REMOVE LISTENER ' + char(10) +
'DROP AVAILABILITY GROUP [' + @name + '];' + char(10) + 'GO' + CHAR(10) + CHAR(10) + CHAR(10)
print @sql;
fetch Next From db_cursor Into @name
END
CLOSE db_cursor
DEALLOCATE db_cursor
This will give me something as the below for each DB in my instance:
ALTER AVAILABILITY GROUP [**DB1**] REMOVE DATABASE [DB1];
ALTER AVAILABILITY GROUP [**DB1**] REMOVE LISTENER N**<>**
DROP AVAILABILITY GROUP [**DB1**];
GO
I cannot find a way to get the availability group and its listener for each DB in each run (The stuff between ** ** needs to be replaced by the AG name/AG listener accordingly). I have searched how to get an AG name/listener for a DB but all of the solutions require a lot of joins which will complicate this query. What's the neatest way to do this?