Friday, February 20, 2009

SQL Server: how to delete non-system databases from a cursor

DECLARE @name nvarchar(200)
DECLARE @stmt nvarchar(200)
DECLARE dbCursor CURSOR FOR SELECT D.name FROM sys.databases D where owner_sid <> 0x01
OPEN dbCursor
FETCH NEXT FROM dbCursor INTO @name
WHILE @@FETCH_STATUS = 0
BEGIN
--next IF is not needed, as cursor specifies that owner_sid <> 0x01 already
--IF @name <> 'master' and @name <> 'model' and @name <> 'msdb' and @name <> 'tempdb'
--BEGIN
PRINT 'Name = ' + @name
SET @stmt = 'DROP DATABASE "' + @name + '"'
PRINT 'stmt = ' + @stmt
EXECUTE sp_executesql @stmt
--END
FETCH NEXT FROM dbCursor INTO @name
END
CLOSE dbCursor
DEALLOCATE dbCursor



Notice couple of tips (at least for someone that doesn't write T-SQL every morning ☺):

- SQL syntax doesn't allow some statements to be run from inside a cursor, so you have to call sp_executesql store proc.
- since '-' is a reserved operator, you have to enclose the DB on quotes to successfully operate on a DB whose name contains '-' or other reserved operator.
- owner_sid <> 0x01 filters out system DB's (preferred over the commented IF)

No comments: