how to change log_reuse_wait and log_reuse_wait_desc - sql-server

I have been created new database and the log file groth very past, and I get error mesaage that the log is full due to 'BACKUP'.
I looked in the differences between this Database and other databases in the SERVER, and I seen that in all databases log_reuse_wait is 0 and log_reuse_wait_desc is NOTHING and in my database log_reuse_wait is 0 and log_reuse_wait_desc is LOG_BACKUP.
I want to change this property in my database to 0 and NOTHING.
How can I do that?

This is a read-only status variable. It tells you why the log cannot be truncated at this point.
You have to remove the cause of that condition instead of just changing the value (which isn't even possible).
Either backup the database log or switch to SIMPLE recovery mode. You should probably read a little on both just to understand the implications.

David W.'s script did not quite work for me. (SQL Server 2008 r2)
I needed to modify it slightly. Using the script as is I got the message that there was no such file for database [master]. Alter the DATABASE as David W. recommends and then switch to the target database and run the DBCC SHRINKFILE() command.
Also the first argument to DBCC SHRINKFILE() must be the logical name of the database log file, which is represented in the following script as logical_file_name_for_LOG
USE [master]
GO
ALTER DATABASE <db name> SET RECOVERY full
GO
ALTER DATABASE <db name> SET RECOVERY SIMPLE WITH NO_WAIT;
GO
USE [db name]
GO
DBCC SHRINKFILE('<logical_file_name_for_LOG>', 0, TRUNCATEONLY)

i found the solution.
even the database is in SIMPLE mode is wait to BACKUP_LOG, so you need to change the recovery mode to FULL and then back to SIMPLE with no wait
USE [master]
GO
ALTER DATABASE <db name> SET RECOVERY full
GO
ALTER DATABASE <db name> SET RECOVERY SIMPLE WITH NO_WAIT;
GO
USE [db name]
GO
DBCC SHRINKFILE('<log file name>', 0, TRUNCATEONLY)

I know this is old, but the answers are wrong.
If the database has recovery mode FULL and that is intended, then do not change it to simple.
The log_reuse_wait_desc says what the state is before the log can be reused or shrinked. In this case it is LOG_BACKUP, meaning that, to shrink the transaction log, you need to backup the transaction log first and shrink it or backup the log and let the SQLServer reuse the log space.
A description of the log_reuse_wait_desc states can be found here

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

Detach and Attach a database in Suspect Mode

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

How to Shrink Transaction log in sql server database in replication

Hi I'm having a production database and its replicated report database. How to shrink the transaction log files in the production database as the log file size is increasing. I had tried DBCC SHRINKFILE and SHRINKDATABASE commands but it does not work for me. I can't detach and shrink and attach back as the db in replication. Please help me in this issue.
First check what is causing your database to not shrink by running:
SELECT name, log_reuse_wait_desc FROM sys.DATABASES
If you are blocked by a transaction, find which one with:
DBCC OPENTRAN
Kill the transaction and shrink your db.
If the cause of the blocking is 'REPLICATION' and you are sure that your replicas are in sync, you might need to reset the status of replicated transactions. To see the status of what the database still think needs to be replicated use:
DBCC loginfo
You can reset this by first turning the Reader agent off (I usually just turn the whole SQL Server Agent off), and then run that query on the database for which you want to fix the replication issue:
EXEC sp_repldone #xactid = NULL, #xact_segno = NULL, #numtrans = 0, #time= 0, #reset = 1
Close the connection where you executed that query and restart SQL Server Agent (or just the Reader Agent). You should be all set to shrink your db now.
The database won't let you remove transaction data that isn't backed up. First you have to back up the transaction log, then you can shrink it.
Do you have a regular backup schedule in place?
If not, I suggest you read this excellent article: 8 Steps to better Transaction Log throughput
Shrink the logfile with dbcc shrinkfile
Then truncate the log file using
Backup databaseName with truncate_only
Then shrink the logfile again
I used Red-Gate's SQL Backup tool to take care of the backing up. Then I just use the management console to issue a shrink command on the log file (telling it to rearrange the pages before releasing unused space).
Works like a charm.

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.

What is the command to truncate a SQL Server log file?

I need to empty an LDF file before sending to a colleague. How do I force SQL Server to truncate the log?
In management studio:
Don't do this on a live environment, but to ensure you shrink your dev db as much as you can:
Right-click the database, choose Properties, then Options.
Make sure "Recovery model" is set to "Simple", not "Full"
Click OK
Right-click the database again, choose Tasks -> Shrink -> Files
Change file type to "Log"
Click OK.
Alternatively, the SQL to do it:
ALTER DATABASE mydatabase SET RECOVERY SIMPLE
DBCC SHRINKFILE (mydatabase_Log, 1)
Ref: http://msdn.microsoft.com/en-us/library/ms189493.aspx
if I remember well... in query analyzer or equivalent:
BACKUP LOG databasename WITH TRUNCATE_ONLY
DBCC SHRINKFILE ( databasename_Log, 1)
For SQL Server 2008, the command is:
ALTER DATABASE ExampleDB SET RECOVERY SIMPLE
DBCC SHRINKFILE('ExampleDB_log', 0, TRUNCATEONLY)
ALTER DATABASE ExampleDB SET RECOVERY FULL
This reduced my 14GB log file down to 1MB.
For SQL 2008 you can backup log to nul device:
BACKUP LOG [databaseName]
TO DISK = 'nul:' WITH STATS = 10
And then use DBCC SHRINKFILE to truncate the log file.
backup log logname with truncate_only followed by a dbcc shrinkfile command
Since the answer for me was buried in the comments. For SQL Server 2012 and beyond, you can use the following:
BACKUP LOG Database TO DISK='NUL:'
DBCC SHRINKFILE (Database_Log, 1)
Another option altogether is to detach the database via Management Studio. Then simply delete the log file, or rename it and delete later.
Back in Management Studio attach the database again. In the attach window remove the log file from list of files.
The DB attaches and creates a new empty log file. After you check everything is all right, you can delete the renamed log file.
You probably ought not use this for production databases.

Resources