I have an installer which as part of the installation creates a SQL Server 2000 (and up) database.
Some users change database server, detach database, ... and want to reinstall.
If the file exists in the default location I get the following error:
Cannot create file 'C:\Program Files\Microsoft SQL Server...\DATA\mydatabase.mdf' because it already exists.
I can solve this by checking the default path first and deleting the files. But how can I do this when the user installs to a remote SQL Server?
I'm looking for something like:
CREATE DATABASE mydatabase WITH OVERWRITE
Edit:
Drop database is not the solution. The database does not exist but the files are still there.
You can test if the database exists with sys.sysdatabase like this
IF EXISTS (SELECT * FROM sys.sysdatabases WHERE NAME = 'mydatabase')
BEGIN
DROP DATABASE mydatabase
END
If you want to test if a specific file is attached to the sql server already, you can also use the system view sys.sysdatabases since it contains the 'filename' attribute containing the mdf file for all databases.
If the file is attached to a different database I think it sounds risky to just overwrite it, and you should probably rather delete the database that is attached to the file. Dropping the database will delete the underlying file.
If the file exists but isn't connected to the sql server you should probably delete it once and make sure that the drops are deleting files on subsequent deletes.
It's 2018 now, and Life and Windows have changed.
So we need a new procedure to get rid of the MDF file
The proper way to delete the file would be to stop the SQL server, delete the file using a file explorer, then start the server again.
See Start, Stop, Pause, Resume, Restart SQL Server Services
And you're done
This happens because somebody might have renamed your database.. but at back .mdf
file is named as first time the database was created.
You can check database name and its corresponding .mdf
file from following command:
SELECT * FROM sys.sysdatabases
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