Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DROP Database with a WHERE clause - TSQL

I want to delete any development databases that are older than 15 days by comparing the date column in a specified table.

Is there a way to write a DROP database query with a WHERE clause or do I have to do a dynamic SQL?

Below is my SQL query:

DROP DATABASE IF EXISTS 
WHERE (SELECT ID FROM master.TableName
        WHERE Date < DATEADD(DAY, -15, GETDATE())
            AND ColumnName1 = 1
            AND ColumnName2 = 0)
like image 389
AznDevil92 Avatar asked Oct 30 '22 18:10

AznDevil92


1 Answers

sp_MSforeachdb will run a statement on every database.

exec sp_MSforeachdb 'IF EXISTS (SELECT ID FROM [?].dbo.TableName WHERE Date < DATEADD(DAY, -15, GETDATE()) AND ColumnName1 = 1 AND ColumnName2 = 0) DROP DATABASE [?];'
like image 160
Marek Koziorowski Avatar answered Nov 15 '22 07:11

Marek Koziorowski