Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop DB but don't delete *.mdf / *.ldf

I am trying to automate a process of detaching and dropping a database (via a VBS objshell.run) If I manually use SSMS to detach and drop I can then copy to database files to another location... however if I use:

sqlcmd -U sa -P MyPassword -S (local) -Q "ALTER DATABASE MyDB set single_user With rollback IMMEDIATE"

then

sqlcmd -U sa -P MyPassword -S (local) -Q "DROP DATABASE MyDB"

It detaches/drops and then deletes the files. How do I get the detach and drop without the delete?

like image 710
Qazxswe Avatar asked Jan 07 '23 08:01

Qazxswe


2 Answers

The MSDN Documentation on DROP DATABASE has this to say about dropping the database without deleting the files (under General Remarks):

Dropping a database deletes the database from an instance of SQL Server and deletes the physical disk files used by the database. If the database or any one of its files is offline when it is dropped, the disk files are not deleted. These files can be deleted manually by using Windows Explorer. To remove a database from the current server without deleting the files from the file system, use sp_detach_db.

So in order for you to drop the database without having the files get deleted with sqlcmd you can change it to do this:

sqlcmd -U sa -P MyPassword -S (local) -Q "EXEC sp_detach_db 'MyDB', 'true'"

DISCLAIMER: I have honestly never used sqlcmd before but assuming from the syntax of how it's used I believe this should help you with your problem.

like image 124
John Odom Avatar answered Jan 10 '23 21:01

John Odom


Use SET OFFLINE instead of SET SINGLE_USER

ALTER DATABASE [DonaldTrump] SET OFFLINE WITH ROLLBACK IMMEDIATE; DROP DATABASE [DonaldTrump];
like image 42
Aurel Havetta Avatar answered Jan 10 '23 20:01

Aurel Havetta