Error 21 when trying to delete a SQL Server DB - sql-server

I had a SQL Server database on an external HDD. I forgot to detach the DB. I do not need it anymore, but I am unable to delete or take it off line.
When I try to delete or take the DB offline, I get the following error.
Msg 823, Level 24, State 2, Line 7
The operating system returned
error 21(The device is not ready.) to SQL Server during a read at
offset 0x00000000012000 in file 'E:\Kenya Air\Monet - Paulus.mdf'.
Additional messages in the SQL Server error log and system event log
may provide more detail. This is a severe system-level error condition
that threatens database integrity and must be corrected immediately.
Complete a full database consistency check (DBCC CHECKDB). This error
can be caused by many factors; for more information, see SQL Server
Books Online.
I have tried to run a DBCC CHECK, but I get the same error.

Try taking the database offline and then online.
Alter database DatabaseName set offline
Then bring it back online after a while
Alter database DatabaseName set online

I would try the system stored procedure sp_detach_db in SQL. From the fine manual:
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.
The OS is reporting exactly what you said in your question: In dropping the database, SQL Server attempts to remove the file from a device that no longer exists. Thus the database cannot be "dropped", per definition. But perhaps it can be detached, because that affects only the system's internal definition of the list of available databases.

Do NOT try to set the database offline and back online - this will eventually make things worse.
Stop SQL Server - move the respective database files (data and logfile(s)) to a different location. Start SQL Server again - eventually the DB will indicate (restore pending) - now delete the DB from SQL server. Next attach the database files back to the server and you should be ok - unless the files are physically corrupt. I have seen this problem numerous times - especially on virtualized SQL instances where SQL server is set to autostart and wasn't shut down in a coordinated manner before a system reboot. A momentary connection problem to either the data or log file can cause this problem. In case your system shows this problem more than once set SQL server to start manually.

I had the same problem, even when I wanted to take the database offline, it gave me this error.
But the problem was solved by restarting SQL.

Related

How to fix Recovery Pending State in SQL Server Database?

How to fix Recovery Pending State in SQL Server Database?
Execute the following set of queries:
ALTER DATABASE [DBName] SET EMERGENCY;
GO
ALTER DATABASE [DBName] set single_user
GO
DBCC CHECKDB ([DBName], REPAIR_ALLOW_DATA_LOSS) WITH ALL_ERRORMSGS;
GO
ALTER DATABASE [DBName] set multi_user
GO
For more info: https://www.stellarinfo.com/blog/fix-sql-database-recovery-pending-state-issue/
When your Database .mdf file name is renamed, this issue is occurred. To solve:
Restart SQL EXPRESS in Services, Pending issue is solved.
In our case it was caused by the disk drive running out of space. We deleted some junk to free space, then fixed the "Recovery Pending" by stopping and restarting the SQL Server Service.
Detach, re-attach, solved !
ALTER DATABASE MyDatabase SET EMERGENCY;
EXEC sp_detach_db MyDatabase
EXEC sp_attach_single_file_db #DBName = MyDatabase, #physname = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\MyDatabase.mdf'
While using SQL Management Studio, there is an intermittent issue when a user is changing the Database Names then sometimes SQL Server uses the same DB file for two different Databases. If SQL Server is in this state then you would be probably seeing the following error if you try Mahesh's answer:
"The process cannot access the file because it is being used by another process"
To fix this issue:
Stop MSSQLServer service from the Services Console MMC
Rename the DB and the Log files (Database Properties -> Files)
In the Object Explorer window in SQL Management Studio, refresh the 'Databases Folder', if you see that there is another Database node (in addition to the one which you are trying to rectify this issue) which is shown in 'Recovery Pending State' then proceed to the next step. If you do not see this error then you need to try something else to resolve this issue
Make a backup of the DB and Log files for new offending node from step 3 and !!Careful!! delete the database
Restore the Db File names which you changed in Step 2
Now start the MSSQLServer service from the Services Console
Re-try the steps from Mahesh's answer
In my case, this affected the secondary server in a High Availability SQL Server cluster.
The primary was Synchronizing but the secondary was Recovery Pending.
After checking in cluadmin.msc, realised that the secondary server wasn't healthy in the cluster.
Then determined Cluster Service had failed to start on the second cluster box after a Windows Update enforced reboot (may have happened because the file share witness was rebooting after a similar Windows Update at the same time).
Starting the Cluster Service brought the databases back into Synchronizing status.
Ensure that the "Log On" account for the "SQL Server (201x)" service (listed in Windows Services (Manager)) has sufficient rights. You may try changing it to another Logon. In my case, changing it from "This account" to "Local System account", restarting the "SQL Server (xxxx)" service and SQL Server Management Studio (SSMS), and logging into SSMS again resolved the issue.
Background (in my particular case):
I had 3 different instances of SQL (2008r2, 2012 and 2014) running on my local PC, and was busy moving a folder (which I later discovered contained some SQL data & log database files) to another PC. Halfway through, I stopped the SQL Services in Service (Manager), hoping that the files would move across without issues - since they would now, no longer be in use. I realized that I needed to confirm the database names, and file locations in SQL (in order to set them up again on the new pc), so I copied the SQL data and log files back (to the original locations). After restarting the PC - the majority of the databases on various instances all showed as: "Recovery Pending" in SSMS. After first trying the procedure from stellarinfo (listed as an answer here by #Mahesh Thorat) on 2 of the databases, and still not having any luck, a post SQL SERVER – Where is ERRORLOG? Various Ways to Find ERRORLOG Location on Pinal Dave's SQL Authority website and the post: Operating System error 5(Access is Denied) on SQL Server Central gave me an idea that it could be rights related after looking at the SQL Errorlog and finding "Operating system error 5: "5(Access is denied.)". Another post Msg 3201, Level 16 Cannot open backup device. Operating system error 5(Access is denied.) at SqlBak Blog seems to support this.
I was using azure, the mdf and log file are in different disk and not attached that disk with which it is not able to figure that files and hence the file Recovery Pending
This could happen due to insufficient permissions for a folder with database files (in my case due to a domain migration).
Just give access to the folder for an SQL service's account.

How to Start SQL Server without TempDB

After the scheduled maintenance when the DBA tried to start the SQL Server;
it failed due to some corruption issue with storage subsystem.
Later on, we identified that the drive on which we had our TempDB's data and log files was corrupt and it was preventing SQL Server from starting successfully.
(Drive was corrupt, so I am unable to read anything from that drive)
So basically we did not have Tempdb database on the server.
And we had to start SQL Server without TempDB
So how do we start the SQL Server without TempDB and how do we fix this?
Before you try anything make sure you backup your data. If one drive failed, another one might fail and leave you without your data. Drives that are purchases at around the same time tend to fail around the same time too.
You need to do that even if some of the data is stored in a RAID array - RAID isn't the same as a backup. If something happens to the array, your best case scenario is that you'll wait for a few hours to recover the data. Worst case, you could lose it all.
The process is described in The SQL Server Instance That Will not Start in the TempDB location does not exist section, and other sites like Start SQL Server without tempdb.
You'll have to start SQL Server with Minimal Configuration. In that state, tempdb isn't used. You can do this with the -f command-line parameter. You can specify this parameter in the service's property page, or by calling sqlservr.exe -f from the command line, eg:
sqlservr -f
Another option is to use the -t3608 trace flag which starts only the master database.
sqlservr -t3608
After that, you need to connect to the server with the sqlcmd utility, eg :
sqlcmd -S myservername -E
to connect using Windows authentication.
Once you do this, you can go to the master database and change the file location of the tempdb files:
USE master;
GO
ALTER DATABASE tempdb
MODIFY FILE (NAME = tempdev, FILENAME = 'E:\SQLData\tempdb.mdf');
GO
ALTER DATABASE tempdb
MODIFY FILE (NAME = templog, FILENAME = 'F:\SQLLog\templog.ldf');
GO
After that, remove the parameters from the service (if you set them there) and restart the service.
Finally, you may have to reconsider the placement of TempDB. TempDB is used heavily for sorting, calculating window functions or in situations where the available RAM isn't enough. Some operations require creating intermediate results, which get stored in TempDB. In general, you should have
multiple tempdb files, although the exact number depends on the server's workload.
How to Start SQL Server without TempDB database?
Step 1: Start the SQL Server in minimal configuration mode.
Click here
to see, "How to start the SQL Server in minimal mode using command prompt".
Step 2: Once SQL Server has started with minimum configuration mode;
connect to SQL Server instance and move TempDB data and log file to a new location.
See, move TempDB data and log files to new location
Step 3: Once you have performed the troubleshooting steps; exit SQLCMD window by typing Quit and Press Enter.
Step 4: . In the initial window click CTRL C and enter Y to Stop SQL Server Service.
Step 5 : Eventually, start the SQL Server Database Engine by Using SQL Server Configuration Manager.
What version of SQL Server it is? One simple solution is to move the tempdb.* files from that location and restart the SQL Server it will create new tempdb files. If you keep those files in that same location it will fail to start.
In SQL Server 2016 If you remove the tempdb physical files, on startup it will see they are missing and rebuild them on the fly in the location they are supposed to be in sysdatabases.

SQL server suspect/Off line mode and Data lost

Suddenly I saw my SQL Server is in suspect/OFF Line mode. That's why I am not able to do any any operation in my db. For this reason I restarted my server (Windows Server 2003) .
But when I get ready I found that some of my data has been lost. I have no any back up of my db.
Is there any way to get back the data that I have lost.
the error log:
Could not redo log record (5108:10151:5), for transaction ID
(0:1552370), on page (1:3679), database '??'
The database may go in suspected/offline mode if the location of datafile and the log file have been misplaced accidentally or intentionally, and so after restart the database is unable to find its datafiles and goes in suspect or offline mode. This can be resolved by bringing the datafile and the log file back to the original path that has been configured for the database. After that, the database can be restored with no loss using the command 'Restore with recovery'. The original path for the datafile and the log file can be found in the error log of the server that contains the database.
Try the solution, hope it will help as it did for me.
In another case, the database may go in suspected/offline mode due to off and restart of the server in middle of a transaction and after the restart the transactions may not be committed or rolled back to a consistent state thus leaving database in an inconsistent state turning it suspected or offline. The solution for this is:
alter database <database name> set emergency dbcc checkdb (repair_allow_data_loss)
As the commnand itself states allow data loss, this command may result in loss of some data from the transaction log and hence we may face a data loss, so it is not recommended for a frequent or unapproved use.
In this case, I suggest you check your log file (LDF). In SQL, this log file records all the INSERT, UPDATE, and DELETE query operations performed on a database.
Suppose you have an LDF file. You can work with Restore and recovery process. I used this process for one of my existing clients & It worked.
https://learn.microsoft.com/en-us/sql/relational-databases/backup-restore/restore-and-recovery-overview-sql-server?view=sql-server-ver16
If you do not have a log file,  you can use stellar repair for SQL this process helps me to recover my data many times.
Thanks

SQL Server Copy Database Issue

I'm running the copy database wizard on a 2008 R2 instance of SQL Server.
The database I want to copy is a SQL 2000 database.
I'm copy that database to another SQL SErver 2008 R2.
The wizard uses SQL authentication for both servers, and both are sysadmins.
When I run it, I get the following error (FYI I have tried both copying the logins and leaving them out):
Event Name: OnError
Message: ERROR : errorCode=-1073548784 description=Executing the query "sys.sp_addrolemember #rolename = N'RandomRoleName..." failed with the following error: "The role 'RandomRoleName' does not exist in the current database.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
helpFile= helpContext=0 idofInterfaceWithError={C81DFC5A-3B22-4DA3-BD3B-10BF861A7F9C}
StackTrace: at Microsoft.SqlServer.Management.Dts.DtsTransferProvider.ExecuteTransfer()
at Microsoft.SqlServer.Management.Smo.Transfer.TransferData()
at Microsoft.SqlServer.Dts.Tasks.TransferObjectsTask.TransferObjectsTask.TransferDatabasesUsingSMOTransfer()
Any help would be appreciated!
Jim
My suggestion is dont use the copy database wizard. Create a full backup of the database on the 2000 server and then restore it on the 2008 server.
If you google "Microsoft.SqlServer.Management.Dts.DtsTransferProvider.ExecuteTransfer Copy Database Wizard" you will find that many many people have gotten this same error or other nearly identical smo errors... no-one appears to have gotten past it.
That's isn't to say its impossible... just, restoring a backup is so much easier then the wizard or troubleshooting the wizard. Good luck.
The copy wizard had missed some security and IIRC it's caused by subtle differences in security tables, principals etc between the 2 versions.
Frankly, the easiest way is to do one of these two:
backup/restore
detach, copy, attach
If you don't have access to the O/S and can't get it, another option is to create the missing role(s) in the background as the copy runs. You have to catch it between the creation of the files and when it tries to reference the roles, but there are a few seconds in which to create them if you keep clicking execute - I managed to create 9 roles.
Unfortunately, you'll end up with the roles in another database too (while yours cannot be used) so those need to be deleted.
Of course, this is only an option when you really can't use the other method.
Though the answer which is using the backup technique solves the problem generally, after facing the same issue several times, I was able to trace down the root of the problem using the Event Viewer of Windows to that the Database Copy wizard, using the SQL Agent, will eventually create a Job for the agent to run, after which the Agent will run using its own credentials (i.e. the credentials that you can look up in Windows Services, in my case, NT Service\SQLAgent$SQL2014)
All you need to do is to go the folder where SQL Server creates DB files (e.g. C:\Program Files\Microsoft SQL Server\MSSQL12.SQL2014\MSSQL\DATA by default for SQL 2014) and give the SQL Agent windows user write/read access on the folder.
The reason can be that a file with the new Database name already exist on the filesystem. We encountered this when we renamed Database X to X_Old, and tried to copy database Y to X. This cannot be done, because database X_Old is still associated with the filename X.
Either delete the conflicting database, or rename the file on the file system.
See http://codecopy.wordpress.com/2012/01/03/error-while-copying-a-database/

Sql server Database Suspected marked?

My sql server marked one database as suspected , on checking i found my mdf,ldf files are missing, but no errors on chkdsk, what it means some virus ?
Either the files were deleted, or they have been moved and a master database backup restored from before the change in location. In both cases the physical files can only be deleted or moved if the database is offline - either because sql server was shut down or the database was closed.
Either of these things is highly unlikely to have happened accidentally. It's unlikely to be a generic virus or trojan as such would either have to specifically delete the files on startup before SQL Server started (assuming your database starts automatically) or shut down the database then specifically delete the files. Given that chkdsk doesn't report errors either it's unlikely to be a disk issue, so it's a virtual certainty that the cause of the error is deliberate database (mis)management.
I think the most likely option is that a dba has decided that the files should be moved elsewhere - typically this is done for space or performance reasons - for instance if a new drive is added to a machine that is running out of space then the database could be moved to that. For some reason a backup of the master database has subsequently been restored from a point before the move.
My first action would be to do a full scan of the system for all mdf/ldf files and (hopefully) locate them. I'd also do a scan of backups and look for the latest master database backup. You could either then try restoring the last master backup and see if that fixed the issue (i'd back up the current master first of course), and failing that, or directly, reattach the missing files.
If you cannot find the mdf/ldf files then your only option is restore from backup. If you don't have a backup then your database is lost.
http://support.microsoft.com/kb/180500
At startup, SQL Server attempts to obtain an exclusive lock on the device file. If the device is being used by another process (for example, backup software) or if the file is missing, the scenario described above will be encountered. In these cases, there is usually nothing wrong with the devices and database. For the database to recover correctly, the device must be made available, and the database status must be reset.
It means someone deleted the files.
They can not be deleted when in use so it happened:
when SQL Server was shut down
the database was closed (Express version usually)
the database was taken offline
All user dbs will share the same folder (edit) by default (end edit) so this is deliberate
The more exotic options include restoring the master db where the databases/MDF files listed in the restored master db do not exist etc. But I doubt it.
In this situation, you can check the SQL Server logs. Go to Management, Click on SQL Server Logs and click on current and check the message.
In my case, I got this:
Error 17207, severity 16, state 1 (it is related to log file deletion or corruption)
Solution:
Set the database into single user mode:
Alter database dbname set single_user
Now set the database into emergency mode:
Alter database dbname set emergency
Repair missing log file or corrupted log file with data loss.
DBCC CHECKDB ('dbname', REAPIR_ALLOW_DATA_LOSS)
Note: You may loss the data by using this command. It also depends on client's approval.
Now set the db in multi user mode;
alter database dbname set multi_user
In SQL Server suspect database is a mode when user unable to connect with database.
At this time user unable to perform any action and can not do anything like no open no backup and no restore etc.
Possible cause for this problem can be one of the following:
1. Database is corrupted
2. Insufficient memory state.
3. unexpected shutdown etc.
4. OS is unable to find the database file

Resources