Unable to delete SQL database - sql-server

While trying to delete a SQL database from SSMS, I am not thrown any error but the progress bar just says executing for about 20 minutes now.
I set the database to Single User mode, tried taking it offline, no active SPID's , DBCC opentran() shows no active/open transactions.. yet still the same result when I try to delete it.
Referred to few posts from users with similar problem .. no luck yet.
Any suggestions much appreciated.

Instead of deleting by right clicking, used the below query to drop the database. Works now!
USE Master;
GO
DROP DATABASE [MyDB]
GO
Note: I could be totally off the mark here but per my understanding the DELETE option just issues a DROP command!

If you are trying to delete a system database then you cant, 2 options below to delete user defined databases:
1.Using SQL Server Management Studio
- In Object Explorer, connect to an instance of the SQL Server Database Engine, and then expand that instance.
- Expand Databases, right-click the database to delete, and then click Delete.
- Confirm the correct database is selected, and then click OK.
Using T-SQL
-Connect to the Database Engine.
-From the Standard bar, click New Query.
-Copy and paste the following example into the query window and click Execute.
USE master ;
GO
DROP DATABASE DatabaseName ;
GO
Incase you wish to drop multiple databases:
USE master ;
GO
DROP DATABASE DatabaseName1, DatabaseName2 ;
GO

USE Master;
DROP DATABASE IF EXISTS [myDatabase]

Related

Moving DataBase from Microsoft SQL folder to App_Data folder (appseting.json)

1. "WebApi": "Data Source=.;Initial Catalog=TaskDB; Integrated Security=true"
2. "WebApi": "Server=(localdb)\\mssqllocaldb;AttachDBFilename=%CONTENTROOTPATH%\\App_Data\\TaskDB.mdf;Trusted_Connection=true;MultipleActiveResultSets=true"
I am trying to move my DataBase from main folder of Microsoft SQL to project folder App_Data, but it does not work for some reason. I do not know why maybe my connection string is wrong. So with number 1 is working fine, but it is in main folder of Microsoft SQL, but with number 2 there is something wrong I guess
The files of database are exclusive in hand of SQL Server. You can not move database when it is online. Taking database offline, requires that no one be connected to database.
First take the database offline then try to move the files. You can take the database offline both using SSMS and query. First line of code kill all active sessions then set database multiple user; but it must be offline before anyone can connect to database so all these code must be executed together.
ALTER DATABASE DatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
ALTER DATABASE DatabaseName SET MULTI_USER
GO
USE master
GO
ALTER DATABASE DATABASE_NAME SET OFFLINE
Be aware that when you move file to another location database could not been brought ONLINE if you do not set new filename before taking the database offline.
Use this code for all of files that you want to move them.
ALTER DATABASE TEST
MODIFY FILE (NAME = 'LOGICAL_NAME', FILENAME = 'New_Directort\Filename.mdf')
After you moved the files then bring online the database with this statement.
ALTER DATABASE DATABASE_NAME SET ONLINE
As you can see this action is not a kind, that can be done without plan. Specially with application code. When trying to do it in application code; then all session including application connection will be lost. then you can not continue the progress.

How to delete (localdb) database if the file is gone

If I run SQL Server Management Studio, and tell it to connect to (localdb)\v11.0, it knows about every database I've ever used, despite the fact that most of the the database files are long gone.
If I ask it to delete one of these databases, it complains that it can't DROP the database because the database file is gone (duhhh). So, how do I clean up this mess and delete all of database references whose assicated database files are gone?
Bob
In this situation, detach the database rather than trying to drop it. In SQL Management Studio, right-click on the database, select "Tasks" then "Detach".
All you need to do is to recreate the instance, tested with SQL 2012 !
just go in command prompt with admin rights and type:
//list the instancies
sqllocaldb i
//stop selected instance
sqllocaldb p "selected instance"
//delete
sqllocaldb d "selected instance"
//recreate or create new one
sqllocaldb c "new instance"
I had the same problem. When designing DB using code first, I simply remove old DBs. It ends up with multiple deleted DB appearing in SQL Server Management Studio. Then when I try to query the DB, it becomes difficult to find the correct DB instance from amongst the deleted.
As IRM suggested, I tried to Detach those deleted DBs, and for some of them it works great!
However still I have several left. Then I tried "Take offline" on those DBs. Each time when I tried to take DB offline, the SQL Server Management Studio crashed. After SQL Server Management Studio restarted, the DB was gone. So try to do "take offline" if detach and delete don't work for you.
I'd collected hundreds of these, and detaching them individually was just too damned tedious.
What I did:
SELECT 'EXEC sp_detach_db ''' + name + ''''
FROM sys.databases
;
This gave me a list of exec commands:
EXEC sp_detach_db 'E:\...\ADATABASE.MDF'
EXEC sp_detach_db 'E:\...\ANOTHERDATABASE.MDF'
EXEC sp_detach_db 'E:\...\ATHIRDDATABASE.MDF'
....
EXEC sp_detach_db 'master'
EXEC sp_detach_db 'model'
EXEC sp_detach_db 'msdb'
EXEC sp_detach_db 'tempdb'
Copy the results back into the command window, highlight everything other than the system databases, and execute.
The accepted answer here says to detach your server, however if you have snapshots you can't detach them, and you run into the same issue deleting them.
You can delete them, however, by creating empty files in the location where sql server thinks the files should be, restarting the sql server service and then trying again.
If you are unsure how to find the physical location, you might find it here: https://dba.stackexchange.com/questions/49811/location-of-the-mdf-file-of-the-database#:~:text=5%20Answers&text=There%20are%20few%20ways%20to,the%20Path%20and%20FileName%20columns.

SQL-Server: The backup set holds a backup of a database other than the existing

I am trying to restore a SQL Server backup file for my database, but it is throwing an error as follow:
The backup set holds a backup of a database other than the existing
My database in SQL Server 2008 and the backup file is in 2005.
What can be the problem?
I too came across this issue.
Solution :
Don't create an empty database and restore the .bak file on to it.
Use 'Restore Database' option accessible by right clicking the "Databases" branch of the SQL Server Management Studio and provide the database name while
providing the source to restore.
Also change the file names at "Files" if the other database still exists. Otherwise you get "The file '...' cannot be overwritten. It is being used by database 'yourFirstDb'".
Either:
1) Use WITH REPLACE while using the RESTORE command (if using the GUI, it is found under Options -> Overwrite the existing database (WITH REPLACE)).
2) Delete the older database which is conflicting and restore again using RESTORE command.
Check the link for more details.
First create a blank database of the same name. Then go for the restore option
Under Options on the left pane don't forget to select
Overwrite the existing database
Preserve the replication settings
That's it
I was facing same problem and found the solution by doing this, using SSMS 2014
Just select the Option Overwrite the existing database(WITH REPLACE)
This causes always due to version incompatibility.
follow these steps to solve:
Step 1: Create a database with your preferred name. (In our case AdventureWorks)
Step 2: Write click on the database and click on Tasks >> Restore >> Database…
Step 3: On the restore screen go to third selection of Options. Now select the checkbox “Overwrite the existing database (WITH REPLACE)”
Step 4: Click OK. It should successfully restore the database.
Note: When you restore a database WITH REPLACE it will overwrite the old database.
USE [master];
GO
CREATE DATABASE db;
GO
CREATE DATABASE db2;
GO
BACKUP DATABASE db TO DISK = 'c:\temp\db.bak' WITH INIT, COMPRESSION;
GO
RESTORE DATABASE db2
FROM DISK = 'c:\temp\db.bak'
WITH REPLACE,
MOVE 'db' TO 'c:\temp\db2.mdf',
MOVE 'db_log' TO 'c:\temp\db2.ldf';
Simple 3 steps:
1- Right click on database → Tasks → restore → Database
2- Check Device as source and locate .bak (or zipped .bak) file
3- In the left pane click on options and:
check Overwrite the existing database.
uncheck Take tail-log backup before restore
check Close existing connection to destination database.
Other options are really optional (and important of course)!
If you are using the script approach and have an error concerning the LDF and MDF files, you can first query the the backup file for the logical names (and other details) of files in the backup set, using the following:
-- Queries the backup file for the file list in backup set, where Type denotes
-- type of file. Can be L,D,F or S
-- info: https://learn.microsoft.com/en-us/sql/t-sql/statements/restore-statements-filelistonly-transact-sql
RESTORE FILELISTONLY FROM DISK = 'C:\Temp\DB_backup.bak'
GO
You will get results similar to the following:
And then you can use those logical names in the queries:
-- Script assumes you want MDF and LDF files restored on separate drives. Modify for your scenario
RESTORE DATABASE DB
FROM DISK='C:\Temp\DB_backup.bak'
WITH REPLACE,
MOVE 'DB' TO 'E:\MSSQL\Data\DB.mdf', -- "DB" is the mdf logical name from query above
MOVE 'DB_log' TO 'F:\MSSQL\Logs\DB.ldf'; -- "DB_log" is LDF logical name from query above
More info on RESTORE FILELISTONLY can be found from the SQL Server docs.
Its because the .mdf and .ldf Files from the original Db were locate at maybe c:\programFile\.... and this info is saved in the Backup!
If you create the same DB on a different SQL Server where the installation is on c:\program Files (x86)\ .... you can not restore as usually. You need to relocate the path for .mdf and .ldf Files.
Therefore:
Create a empty DB on the new Server
Right click on the empty Db > Tasks > Restore > Database > click Device select your .bak Files > Select Db to restore into
click on Files at left side > Select "Relocate all Files to Folder"
click Options on the left site > click on Overwrite
Done!
Hope it helps!
I had ran into similar problem today. Tried all the above solutions but didn't worked. So posting my solution here.
Don't forget to uncheck Tail-long Backup before restore
Hope it help others too!
Also as important is to make sure that, your database name matches the data base name in the backup you are trying to restore. If it does not match, you will get the same error.
system.data.sqlclient.sqlerror:The backup set holds a backup of a database other than the existing 'Dbname' database
I have came across to find soultion
Don't Create a database with the same name or different database name !Important.
right click the database | Tasks > Restore > Database
Under "Source for restore" select "From Device"
Select .bak file
Select the check box for the database in the gridview below
To DataBase: "Here You can type New Database Name" (Ex:DemoDB)
Don't select the Existing Database From DropDownlist
Now Click on Ok Button ,it will create a new Databse and restore all data from your .bak file .
you can get help from this link even
Hope it will help to sort out your issue...
Before doing anything else, confirm if your backup is Full or Differential. If you're trying to create a new database out of a differential backup, no matter what you do you will encounter the error.
Same issue with me.The solution for me is:
Right click on the database.
Select tasks, select restore database.
Click options on the left hand side.
Check first option OverWrite the existing database(WITH REPLACE).
Go to General, select source and destination database.
Click OK, that's it
I was just trying to solve this issue.
I'd tried everything from running as admin through to the suggestions found here and elsewhere; what solved it for me in the end was to check the "relocate files" option in the Files property tab.
Hopefully this helps somebody else.
Some of you have highly over complicated this. I found this to be extremely simple.
1) Create a database with the same name as your .bak file database name !Important
2) right click the database | Tasks > Restore > Database
3) Under "Source for restore" select "From Device"
4) Select .bak file
5) Select the check box for the database in the gridview below
6) Under "Select a Page" on the right Select "Options"
7) Select the checkbox labeled "Preserve the replication settings(WITH KEEP_REPLICATION)
Now Go back to the General page and click OK to restore the database...That is it.
I had to create new db on my local for testing & i had a back up from my prod. I created the db first and tried to run the BAK on top of the new db which produced this error for me. I deleted the db and restored it while sourcing the new db name in the restore screen itself. The db was automatically created on restore.
I got work done through alternate way, using Generate scripts. That did work for me as Backup-Restore didn't help to resolve the issue due to same error.
In the Options, change the "Restore As" file name to the new database mdf and ldf. It is referencing the source database .mdf and .ldf files.
You can restore to a new DB, verify the file name syntax, it ll be in the log file, for the new SQL version ll be a "_log" suffix
ad check the overwrite the existing database flag in option tab
Fabio
This helped me to import the back-up file from the system drive
Create a database with the same name(preferably) as your .bak file database name
Right click the database > Tasks > Restore > Database
Under "Source for restore" select "From Device"
Select the .bak file selecting the path from the system
Select the check box for the database in the list box below
Under "Select a Page" on the right Select "Options"
Select the checkbox labeled "Preserve the replication settings(WITH KEEP_REPLICATION)
Select the checkbox for Overwrite the existing database(WITH REPLACE)
Now Go back to the General page and click OK to restore the database...
Im sure this problem is related to the files and folders permissions.
I was trying to restore a production database to a staging database on the same server.
The only thing that worked in my case was restore to a new blank database. This worked great, did not try to overwrite production files (which it would if you just restore production backup file to existing staging database). Then delete old database and rename - the files will keep the new temp name but in my case that is fine.
(Or otherwise delete the staging database first and then you can restore to new database with same name as staging database)
instead of click on Restore Database click on Restore File and Filegroups..
thats work on my sql server
I had the same issue but on PS. I leave it here in case someone is trying to do the same
Restore-SqlDatabase -ServerInstance "<your instance name>" -Database "<your db name>" -BackupFile "<backup file route>.bak" -ReplaceDatabase
remember to use Set-ExecutionPolicy Unrestricted -Force and import import-module sqlps. Don't forget to set back your Execution Policy back to restricted once you are done.
Usually dealing with .bak files are coming with headaches, a more straight forward way is using sqldump files to transfer databases.
Generate script of current database you want to move or copy.
Instead of entire database, select All Tables.
From the option menu choose save as script, and click on advance button and set the following configs (I am suing MSSQL 2016):
Now, where you want to import these data, create a new database, switch to this new database (I mean set it as default)
Finally run the script, all table and data will be imported.
Good Luck.
List item

Is there some way for me to generate SQL Scripts from an already existing database?

Say I already created my database but forgot to save the sql commands do create it.
How could I reverse engineer the code from an already existing database?
I'm using Microsoft SQL Server Express 2008.
You can do this pretty easily by using SQL Server Management Studio (SSMS) - it's available for free if you don't already have it installed.
Connect to the database
Expand out Databases > YourDataBaseName.
Right-click on the database and select the option "Script database as" then "Create To" then finally "File".
That will create the necessary scripts to recreate your database.
To script out all the tables in your database:
Right-click on the database node
Select "Tasks" then "Generate Scripts".
When the wizard appears, click Next.
Select the database. At this point you can check the "Script all objects in the selected database" which does exactly what it says, or if you leave it unchecked you will get the option later in the process to pick which items are scripted.
Click next. Now you're given some scripting options.
I'd suggest scrolling down the list and checking the option to Script Indexes/Script Triggers. You can also script the data if necessary (though I wouldn't do this if you've got a lot of data in your database).
Modify any options you'd like and click Next.
Select the database types you'd like to script (Users/Tables/Views). Click Next.
Now you've got the opportunity to select more specific items. Hit Next and repeat the process of any of your other database types.
Hit next one more time, then select where you'd like the script written to. You get the chance to review your selections.
Click Finish.
Here's a link for the 2008 version SSMS Express 2008
Your RDBMS comes with some sort of "dump" tool that will give you the structure and content of your database, in the form of SQL statements.
As others have mentioned, if you have SQL Management Studio (you should, it's free as part of SQL Server Express). Fire it up, connect to your instance then expand the Database tree.
Right click on your database and select Tasks->Generate Scripts..
Click next, then Next again (which selects all objects in the database by default), pick an output option (defaults as "Save to File"), click next and voila!
If you also want to script the data as well as the schema, in the "Set Scripting Options" window, click on the Advanced button, scroll down to "Types of data to script" (just above the Table/View Options header) and select "schema and data".
[Edit] Tested - The Generate Scripts option exists and works in the (free) 2008 R2 edition of SSMS. See the link in my comment below for the URI for the R2 version.

Trying to restore via t-sql script. Exclusive access could not be obtained because the database is in use

I'm trying to restore backups of our production databases to our development server. When I run the following script which has previously worked:
RESTORE DATABASE M2MDATA01 FROM DISK = 'C:\Install\SQLBackup\M2MDATA01.SQLBackup' WITH REPLACE,
MOVE 'M2MDATA01' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\M2MData01.mdf',
MOVE 'M2MDATA01_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\M2MData01.ldf'
I get the following error:
Error 12/21/2009 9:06:09 AM 0:00:00.000 SQL Server Database Error: Exclusive access could not be obtained because the database is in use. 5 0
However, I have no idea how what could possibly be using it. How can I tell?
Check what's connected (the easy way)
SELECT * FROM sys.sysprocesses S WHERE S.dbid = DB_ID('M2MDATA01')
Note: sysprocesses can not be emulated using dmvs...
Edit, check for locks too
SELECT * FROM sys.dm_tran_locks L WHERE L.resource_type = 'DATABASE' AND L.resource_database_id = DB_ID('M2MDATA01')
In SQL Server Management Studio, go to Management => Activity Monitor. This will show you all processes that are connected to all databases, and allow you to kill these processes (only recommended as a last resort).
Profiler is one option.
From Sql Server Management Studio, select Tools|Sql Server Profiler.
Connect to the server instance that the database you are working with is on.
Switch to the Event Selection tab
check the checkbox below the grid labeled "Show all columns"
In the grid find the DatabaseName column and check the entire column.
(optional) press the Column Filters button and filter to the database name you are working with.
This should at least tell you if something is using the database in question.
Easiest solution here is to delete the database and select the "close existing connections" checkbox before hitting okay. Then the restore will work just fine. It's just DEV right? :}
If you're restoring a db, do you really care who is connected? Or what is being done with those connections? I would think not. Just "kick everyone out" by setting the database into single user mode and then restore the database.
USER master
GO
ALTER DATABASE M2MDATA01
SET SINGLE_USER
--This rolls back all uncommitted transactions in the db.
WITH ROLLBACK IMMEDIATE
GO
RESTORE DATABASE M2MDATA01
FROM DISK = 'C:\Install\SQLBackup\M2MDATA01.SQLBackup'
WITH REPLACE,
MOVE 'M2MDATA01' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\M2MData01.mdf',
MOVE 'M2MDATA01_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\M2MData01.ldf'
GO
Now, one additional item to be aware of. After you set the db into single user mode, someone else may attempt to connect to the db. If they succeed, you won't be able to proceed with your restore. It's a race! My suggestion is to run all three statements at once in a single batch.

Resources