How can I programmatically drop a SQL Server database from .NET code - sql

I'm trying to drop a SQL Server database from .NET code. I've tried using the SMO classes but get an exception saying the database is in use.
Then I tried executing a query (opening a SqlConnection, executing a SqlCommand), along the lines of:
ALTER DATABASE foo SET SINGLE_USER WITH ROLLBACK IMMEDIATE
(pause)
DROP DATABASE foo
But still I get an exception saying the database is in use.
How do I do this? (Or, how does SQL Server Management Studio implement the Drop database and close existing connections?)

You need to make sure you're doing it from the master database:
USE master
GO
ALTER DATABASE foo SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
DROP DATABASE foo
GO
Should work. By the way, SQL Server Management Studio allows you to view the script it generates for all command in the GUI. For example, in the "Delete" window, there's a "script" menu item at the top that'll show you the script you can use.

This may be a stupid question, but in your connection string, are you connecting to the database you're trying to drop, or to the Master database on the same server? If you're trying to drop the database you're actively connected to, it would certainly explain the error.
Also, keep in mind that ADO.NET keeps connections open using connection pooling. So even though you aren't actively running queries using a given connection string, connections may still be open.

Related

Can’t See Sql Databases After Creating in VSPM

I am attempting to create a new database in an existing sql server from code first. I used package manager to enable migrations, add a migration, then update database. The three methods executed without any errors and I got the traditional massages afterwards. However, when I look in either MSSSMS or Server Explorer I don’t see the database. I tried re-running the update database command and got the migration has already been applied. Any suggestions?
Update:
I've figured out that the project is adding the database to localdb. However, I have a connection string in the app.config file.
Probable causes are:
the database was never created
you use a login that can't see the database. Using Windows authentication/sa might allow you to see it and create user mappings for other logins.
you have multiple instances of sql running and you're connecting to the default instance while the database what created on a named instance
you accidentally created the database on another server
you connect to master by default with your software and instead of creating a database the database structure was created in the system database master
I've been working with MS sql for more than a decade and have struggled with issues like these, but in the end I could always explain what happened; if SQL returns it executed a query succesfully id did.

Accidentally dropped SQL Server database connection

I accidentally dropped SQL Server database connection in SQL Server Management Studio. After i dropped the Connection and pushed "OK" the database was put into single user mode and then the database was taken offline and not shown in the object-explorer.
Is there any Point to rettach the database? I dont find any .BAK Datas or the Databasename in the Restore Options.
I tryed already, but get errors
USE master;
GO
ALTER DATABASE MyDB SET MULTI_USER
GO
I hope there is something i can do. Thx
EDIT:
Steps i did right Click on the Database -> Task -> Detach , than i was in the following Windows and clicked on "Drop Conections" and clicked "OK" and than she went into single user mode and went offline. But after a refresh i didnt saw her in my object Explorer. I followed this steps:
Getting exclusive access to restore SQL Server databases
so any way to get into single user mode to get her back?
See if any *.mdf files exist in file system for the dropped database. If you find, restore.

Database '[DatabaseName]' already exists. Choose a different database name

I'm following this guide illustrating a code-first approach with Entity Framework core. Migrations were functioning correctly until, at some point, I deleted my .mdf file. Since then, executing Update-Database (to apply my migration) throws the following error:
Database 'DatabaseName' already exists. Choose a different database name.
Where exactly is this database? How can I remove it permanently?
According to this answer, I need to detach my database from Sql Server, but I'm not sure how to do that now. In Sql Server Management studio, If I execute sp_detach_db DatabaseName it throws error The database 'DatabaseName' does not exist. Supply a valid database name.
Thanks in advance.
UPDATE
I see I can also reproduce this database already exists error if I have the database attached in SQL Server Management Studio, and execute the Update-Database command. After I close the management studio, the migration applies without this error. Very confusing to me.
Seems like an instance of LocalDB is still running in the background. Execute the following commands in the console to stop and delete the instance.
sqllocaldb stop
sqllocaldb delete
The Update-Database command should now have no problems.
Please look at the SQL Server Object Explorer (Visual Studio -> View -> SQL Server Object Explorer). If it contains the 'DatabaseName' database then please try to delete it.
If you create your database with SQL (meaning DB already exists), put the line DROP DATABASE [databaseName] at the beginning of the file databaseName.sql
This will delete the whole DB and its definition (schema), now you can start with creating your new DB.
Another guess.. if you have restored the database then your user login will not work anymore because of the orphan. Try to remove user and create it again. you will get the same error if your migration cannot access the database.
It might be a local DB. Try connecting to your local DB
(LocalDb)\MSSQLLocalDB
And seeing if the DB is located there. You may need to delete it from SSMS
Try to modify the number code of 'xxxxx-20170604092712' in Web.config file,
and then 'update-database' again. This worked for me.
I restore my database to another server, To fix this I had to remove from the DB under Security the previous users and create them again
I am using MSSQLLocalDB. I've encountered this issue after restoring the backup of a DB using the Azure Data Studio.
When I connected using Microsoft SQL Management Studio, I've noticed that my DB was in a SINGLE_USER mode (I have not noticed it in the Azure Data Studio).
Changing the mode to MULTIPLE_USER fixed the issue for me:

Offline database can't be restored: Exclusive access could not be obtained

I'm practicing a SharePoint 2010 to 2013 migration and having trouble restoring a database. After backing up a database on a SP2010/SQL 2008 server, I'm trying to restore it to a database I've freshly created on my SP2013/SQL 2012 server.
Though the UI, I've taken the destination database offline. I select the .bak file, select my destination database, and attempt the restoration. I get an error: Exclusive access could not be obtained because the database is in use.
Why is this happening? I've taken the database offline, I don't see how it could possibly be in use.
In the restoration window, I've tried going to Options and selecting Overwrite the existing database (WITH REPLACE) as well as Close existing connections to destination database.
Still the same error message. How do I get past this error?
Try this, I had the same issue last week!
ALTER DATABASE [Test4] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
RESTORE DATABASE [Test4]
FROM DISK = 'c:\test4.BAK'
WITH MOVE 'Test4_Data' TO 'c:\data\Test4.mdf',
MOVE 'Test4_Log' TO 'c:\data\Test4_log.ldf'
detailed explanation can be found at http://www.mssqltips.com/sqlservertip/1407/getting-exclusive-access-to-restore-sql-server-databases/

Database is not accessible after 'taking it offline' process failed

I was trying to detach the DB when it gave me an error that it is currently in use. Hence, I tried to take my DB offline but it failed saying
'an exception occured while executing a transact SQL statement or batch
-> ALTER DATABASE failed because a lock could not be placed on database 'myDB'. Try again later.
ALTER DATABASE statement failed. (Microsoft SQL Server, Error: 5061)'
Now if I try and access the DB it says it is not accessible. What can I do to make my DB accessible again?
My aim was to detach the DB, relocate its secondary database file to a new drive and reattach it (simply because of space issues).
Try following steps.
Restart the SQL server service using services.msc console.
Now connect to your server using SQL Server Management Studio.
Run following command in query analyzer
ALTER DATABASE `YOURDATABASE_NAME`
SET SINGLE_USER WITH ROLLBACK IMMEDIATE
Now Right-click the database name, point to Tasks, and then click Detach. The Detach Database dialog box appears
OR
5. Run your command to Relocate the secondary database.
Set the database mode to multi user again
ALTER DATABASE `YOURDATABASE_NAME` SET MULTI_USER
Hope this helps.
As an alternative to step one in Furqan's answer, you might not need to restart the SQL Server instance, but only the SQL Server Management Studio instance, which was used to initiate the "Take Offline" task.