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)
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 [?];'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With