Detach and Attach a database in Suspect Mode - sql-server

Problem:
Backups were failing in one of our servers with the below message: (Backups are taken via Netbackup)
Could not allocate space for object 'dbo.backupfile'.'PK__backupfi__57D1800AC4FFEEA3'
in database 'msdb' because the 'PRIMARY' filegroup is full. Create disk space by deleting
unneeded files, dropping objects in the filegroup, adding additional files to the
filegroup, or setting autogrowth on for existing files in the filegroup.>
DBMS MSG - SQL Message <3009><[Microsoft][ODBC SQL Server Driver][SQL Server]Could not
insert a backup or restore history/detail record in the msdb database. This may indicate a
problem with the msdb database.
On checking, I could see that the Mount Drive on which the primary data file of msdb resides, was full (Total size: 99GB, Free space: 0 bytes). The drive didn’t have any unwanted files which I could delete and gain some easy disk space. So I looked around the Drive and found a database log file which was 6GB in size and of which more than 5.5GB was free. I thought shrinking it will free up quite some space in the Drive and solve the problem for the time being. But when I attempted the shrink on the Log file, I got an error message saying ‘It has been marked SUSPECT by recovery’. Fearing the worst, I refreshed the database list in the Object Explorer and Bingo..!! there it was, marked as ‘Suspect’

Solution:
I checked the other drives in the server and found one with ample free space. So my next attempt was to detach the DB (say ‘XYZ’), move its log file to the other drive and then attach it. This would release enough space in the drive and would also let the DB recover from Suspect mode. So I tried detaching the DB, but it didn’t work.
Cannot detach a suspect database. It must be repaired or dropped. Cannot be opened as the DB is in Suspect mode
So I tried to bring it to Single User mode:
Execute the script to put the DB to single user mode
USE master;
GO
ALTER DATABASE [XYZ]
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;
GO
Set the database to offline.
-- Take the Database Offline
ALTER DATABASE [XYZ] SET OFFLINE WITH
ROLLBACK IMMEDIATE
GO
Now I was able to successfully detach the Database. After detaching, I copied the log file to the other drive which had enough free space. Then I tried to attach the DB back. But on attaching, It gave the below error msg:
Error: 5123 CREATE FILE encountered operating system error 5A(Access denied.)
To resolve it, the following are the steps I did:
Right click on the .mdf file -> Properties
Under the ‘Security’ Tad, press Continue
Click ‘Add’ to include you in ‘Groups or user names’
Give you login Id in the Pop -up that came up, ‘Check Names’ and ‘Ok’
After adding your login, click on it, and in the Box below (Permissions for User), check Allow ‘Full Control’ for the User. It is very important that you Check ‘Full control’ because by default the user will be having only ‘Read’ and ‘Read & Execute’ permissions. And if you try attaching with just those default permissions, you’ll again get Access denied errors.
After this, I was able to successfully attach the DB, and its status was found to be ‘Normal’.
Hope this will help somebody :)

Never detach a database in this situation. I also suggest not to Run DBCC CHECKDB with repair allow data loss option as you may loss your important data. You can check this reference: https://community.spiceworks.com/topic/1078473-sql-server-database-in-suspect-mode

Try to use master database It will reset the state of the database you can work with it.
EXEC sp_resetstatus your_db_name
ALTER DATABASE your_db_name SET EMERGENCY
DBCC checkdb (your_db_name)
ALTER database your_db_name SET SINGLE_USER with ROLLBACK IMMEDIATE
DBCC CHECKDB (your_db_name, REPAIR_ALLOW_DATA_LOSS)
Alter database your_db_name SET MULTI_USER

Related

Can we remove Memory Optimized file group from database

I checked In sql server 2019(15.0.2070.41) and tried to remove with bellow mentioned command:
Alter database InMemoryCheckpoint
Remove file InMemoryCheckpointDF
Alter database InMemoryCheckpoint
Remove filegroup InMemoryCheckpointDF
You can't remove a memory-optimized filegroup.
The following limitations apply to a memory-optimized filegroup:
Once you use a memory-optimized filegroup, you can only remove it by
dropping the database. In a production environment, it is unlikely
that you will need to remove the memory-optimized filegroup.
https://learn.microsoft.com/en-us/sql/relational-databases/in-memory-oltp/the-memory-optimized-filegroup?view=sql-server-ver15
!!! Please use this method in case of corrupted database that contains memory optimized table (you can't use DBCC check on databases that contains memory optimized tables) !!!
WARNING: This is an unsupported operation. There have been reports of unrecoverable log corruption when using this.
It's a hack method and it's risky. Microsoft didn't verified this solution
Before doing anything take backup
1- Delete memory optimized tables
2- Detach Database
3- Create new database with same files without memory optimized filegroup
4- Modify database files and change it to detached database (mdf,ldf,ndf) files
alter database test1 modify file (name='test1' , filename='C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\test.mdf')
alter database test1 modify file (name='test1_log' , filename='C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\test_log.ldf')
5- Now try to to repair database:
alter database test1 set emergency
alter database test1 set single_user with ROLLBACK IMMEDIATE;
dbcc checkdb(test1,repair_allow_data_loss)
alter database test1 set multi_user
alter database test1 set online
6- After successfully repair database remove memory optimized filegroup from database
ALTER DATABASE [test1] REMOVE FILEGROUP [memory_optimized_filegroup_0]
Follow steps correctly for prevent log corruption
Step 4: Alter log file name must be done correctly
Step 5: DBCC is Important to prevent corruption
Also for getting best result:
Don't use database while doing steps (Insert - Update - Changing
Schema)
do CHECKPOINT to flush log to data file then shrink log file
you will never have log corruption issue
Don't forget:
Before using your database do this steps for checking issue:
Insert or update 1 row in database
Do CHECKPOINT
Restart server
If database got online i think you did all steps correctly else Restore database from backup and forget about removing memory optimized filegroup
Used these commands and they worked fine for me:
USE [<dbname>]
GO
ALTER DATABASE [<dbname>] REMOVE FILE [<filename>]
GO
ALTER DATABASE [<dbname>] REMOVE FILEGROUP [<Group Name>]
GO

Truncate SQL Server transaction log file

In my local C: drive I have a ldf file for a database that is hosted on one of our servers. I have a local copy of one of the databases that is 1 gb and a ldf (log file) of that database that is 16gb. It is eating up a lot of my local space on my hard drive. I would like to truncate that file. A lot of what I read online is don't, but it seems that they are talking about files on the server that the database is on. That isn't the case here, it is on my local machine.
The location of the file on my machine is:
C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA
How come I have a copy of that log file locally and also that database locally?
How would I go about truncating this file?
Thanks!
Go to the Object Explorer pane in SSMS and right click on the database in question. Choose tasks -> shrink -> files. Change the file type option to Log, click the "Reorganize pages before releasing unused space" option, and set the value to 1 MB. Hit OK.
If this doesn't work, check to see if your database is set up with a Full database recover model. Right click the database and go to properties. Choose Options, and check the Recover model option. Set to simple (if you can!!!), then shrink the logs.
The another option you can try is to use WITH TRUNCATE_ONLY:
BACKUP LOG databasename WITH TRUNCATE_ONLY
DBCC SHRINKFILE ( adventureworks_Log, 1)
but don't try this option in live environment, the far better option is to set database in simple recovery. see the below command to do this:
ALTER DATABASE mydatabase SET RECOVERY SIMPLE
DBCC SHRINKFILE (adventureworks_Log, 1)

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 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

How to recover database from MDF in SQL Server 2005?

I have an MDF file and no LDF files for a database created in MS SQL Server 2005. When I try to attach the MDF file to a different SQL Server, I get the following error message.
The log cannot be rebuilt because there were open transactions/users when the database was shutdown, no checkpoint occurred to the database, or the database was read-only. This error could occur if the transaction log file was manually deleted or lost due to a hardware or environment failure.
I would like to accomplish any one of the following options:
Attach the database without data loss (unlikely but would save me some time).
Attach the database with data loss (whatever transactions were open are lost).
Recover the schema only (no data) from the MDF file.
What SQL commands can I try to get my database going again?
I found the following document on Experts Exchange.
patrikt:
You will have data loss but it can be done.
1. Detach database and move your mdf to save location.
2. Create new databse of same name, same files, same file location and same file size.
3. Stop SQL server.
4. Swap mdf file of just created DB to your save one.
5. Start SQL. DB will go suspect.
6. ALTER DATABASE yourdb SET EMERGENCY
7. ALTER DATABASE yourdb SET SINGLE_USER
8. DBCC CHECKDB (yourdb, REPAIR_ALLOW_DATA_LOSS)
9. ALTER DATABASE yourdb SET MULTI_USER
10. ALTER DATABASE yourdb SET ONLINE
Here are details that cover parts 2) and 3) in case re-creating log doesn’t work which can happen if MDF file is corrupted.
You can recover data and structure only by reading MDF file with some third party tool that can de-code what’s written as binary data but even with such tools you can’t always do the job completely.
In such cases you can try ApexSQL Recover. From what I know this is the only tool that can do this kind of job but it’s quite expensive.
Much better idea is to try to recover these from any old backups if you have any.
FROM a post at SQL Server Forums Attaching MDF without LDF:
If you want to attach a MDF without LDF you can follow the steps below
It is tested and working fine
Create a new database with the same name and same MDF and LDF files
Stop sql server and rename the existing MDF to a new one and copy the original MDF to this location and delete the LDF files.
Start SQL Server
Now your database will be marked suspect 5. Update the sysdatabases to update to Emergency mode. This will not use LOG files in start up
Sp_configure "allow updates", 1
go
Reconfigure with override
GO
Update sysdatabases set status = 32768 where name = "BadDbName"
go
Sp_configure "allow updates", 0
go
Reconfigure with override
GO
Restart sql server. now the database will be in emergency mode
Now execute the undocumented DBCC to create a log file
DBCC REBUILD_LOG(dbname,'c:\dbname.ldf') -- Undocumented step to
create a new log file.
(replace the dbname and log file name based on ur requirement)
Execute sp_resetstatus
Restart SQL server and see the database is online.
UPDATE: DBCC REBUILD_LOG does not existing SQL2005 and above. This should work:
USE [master]
GO
CREATE DATABASE [Test] ON
(FILENAME = N'C:\MSSQL\Data\Test.mdf')
FOR ATTACH_REBUILD_LOG
GO
have you tried to ignore the ldf and just attach the mdf:
sp_attach_single_file_db [ #dbname = ] 'dbname' , [ #physname = ] 'physical_name'
i don't know exactly what will happen to your open transactions (probably just lost), but it might get your data back online.
-don
See here : Rebuild master and restore system databases from complete disk failure which has a very nice explanation
Just had this problem myself, but none of the above answers worked for me.
But instead, I found this which worked a treat and so I thought I'd share this for everyone else:
http://www.kodyaz.com/articles/sql-server-attach-database-mdf-file.aspx
Found a another way that works completely:
Create new database with same name to default database location.
Stop SQL server.
Copy old mdf file to overwrite newly created mdf file and delete new ldf file
Start SQL Server, database will be in emergency mode
Detach the emergency mode database
Copy original ldf file to default database location (where new LDF file as created and deleted under step 3 above.
Attach the database MDF file.
I got a working database after trying all of the above that failed for me.
I hope it is easy to do so,
Open SQL Server
Click New Query
Execute the following query
sp_attach_single_file_db #dbname='dbname',#physname='C:\Database\dbname.MDF'
Where dbname is you want to show in Object Explorer, where #physname is the local filepath location of your mdf file.
Hope it will help someone, i done by above, got both structure and also data.
Tested in Sql Server 2000 and 2008. In Sql Server 2000 it is not working, but works perfectly in 2008.

Resources