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

让人想犯罪 __ 提交于 2020-07-22 05:06:04

问题


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?


回答1:


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.




回答2:


Might it be best to detach the database rather than drop it? If you drop the database, that implies delete

Note, however, that this will leave your hard disk cluttered with database files you no longer want - in a couple of years time your successor will be running out of space and wondering why the disk is full of MDF files he doesn't recognise



来源:https://stackoverflow.com/questions/33154141/drop-db-but-dont-delete-mdf-ldf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!