April 26, 2024

SamTech 365

PowerPlatform, Power Apps, Power Automate, PVA, SharePoint, C#, .Net, SQL, Azure News, Tips ….etc

Delete all User databases with TSQL

Again, if you want to delete all user databases with a single TSQL script, you can achieve this easily by using this script

DECLARE @command nvarchar(max)

SET @command = ''

SELECT  @command = @command

+ 'ALTER DATABASE [' + [name] + ']  SET single_user with rollback immediate;'+CHAR(13)+CHAR(10)

+ 'DROP DATABASE [' + [name] +'];'+CHAR(13)+CHAR(10)

FROM  [master].[sys].[databases] 

 where [name] not in ( 'master', 'model', 'msdb', 'tempdb');

SELECT @command

EXECUTE sp_executesql @command

Please ensure to backup all you databases before (how to back up everything)

Use this script at your own risk