Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to drop and create database in sql server

I'm working with SQL Server 2008 and I can't seem to do drop and create a database.

I've tried a few different ways but I always end up failing to drop or trying to "use" before it seems to be created.

My current attempt looks like this.

use master; GO IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'test') BEGIN DROP DATABASE [test]; END GO CREATE DATABASE [test]; GO use [test]; GO 

The GO were suggested on a MS forum as a way to stop some issues that occur when selecting databases.

With this I currently get the output (with a ore existing database of the same name) of:

Msg 3702, Level 16, State 4, Line 3
Cannot drop database "test" because it is currently in use.
Msg 1801, Level 16, State 3, Line 1
Database 'test' already exists. Choose a different database name.
Msg 2714, Level 16, State 6, Line 2
There is already an object named 'staff_type' in the database.

With the last 2 lines repeated for every table in my database.

like image 820
TrewTzu Avatar asked Oct 03 '12 05:10

TrewTzu


People also ask

How do I force drop a database in SQL Server?

To remove a database from the current server without deleting the files from the file system, use sp_detach_db. USE master; ALTER DATABASE [databasename] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [databasename] ; Note, database backups will not be deleted as part of the process documented above.

Can't drop existing database SQL?

If you want to delete the database, you will get this error if there is an open session on the database. First, set the database to single_user mode. Then you can delete it.

Why can't I DROP TABLE in SQL?

The reason SQL won't let you drop a table in this situation is because the allocation pages/extent chain appears to be damaged or cross-linked in some way. So SQL Server thinks that there is actually data from other tables in pages/extents belonging to the problem object.


1 Answers

We usually get this error If You've opened any query window with connection to this database, so make sure you close all your opened query windows connected to db which you're trying to drop.

Don't use the database which you're trying to drop. use master to drop any user database that is a good practice.

Make sure No other process is attach to the database you're trying to drop.

EXEC sp_who2 --Run kill spid for each process that is using the database to be dropped. kill <<processid>> -- Kill 57 

Use EXEC sp_who2 and check the DBName column, your database name should not appear in the list, if it appears kill the process using kill <<processid>> then try to drop.

Try this code.

use master GO  IF EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name = N'test') DROP DATABASE [test] GO  CREATE DATABASE [test] GO  use [test] GO 
like image 124
Vishwanath Dalvi Avatar answered Oct 06 '22 15:10

Vishwanath Dalvi