Last active
December 20, 2015 23:29
-
-
Save aweigold/6213132 to your computer and use it in GitHub Desktop.
Deleting a database remotely with SQL Serverhttp://www.adamweigold.com/2011/11/deleting-database-remotely-with-sql.htmlThis should never be done on a production server, as it will open up security risks. This is useful for integration tests and utilities. Replace %dbName% appropriately
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
BEGIN | |
IF EXISTS (SELECT * FROM tempdb.sys.tables WHERE name LIKE '#dbFiles%') | |
DROP TABLE #dbFiles | |
END | |
EXEC master.dbo.sp_configure 'show advanced options', 1 | |
RECONFIGURE | |
EXEC master.dbo.sp_configure 'xp_cmdshell', 1 | |
RECONFIGURE | |
DECLARE @dbFile VARCHAR(8000) | |
DECLARE @cmd VARCHAR(8000) | |
SELECT physical_name INTO #dbFiles FROM %dbName%.sys.database_files | |
ALTER DATABASE %dbName% SET OFFLINE WITH ROLLBACK IMMEDIATE | |
DROP DATABASE %dbName% | |
SELECT * FROM #dbFiles | |
DECLARE cur CURSOR LOCAL FOR | |
SELECT physical_name FROM #dbFiles | |
OPEN cur | |
FETCH next FROM cur INTO @dbFile | |
WHILE @@FETCH_STATUS = 0 BEGIN | |
SET @cmd = 'del "' + @dbFile + '"' | |
EXEC master.dbo.xp_cmdshell @cmd | |
FETCH next FROM cur INTO @dbFile | |
END | |
CLOSE cur | |
DEALLOCATE cur | |
DROP TABLE #dbFiles |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment