As part of continued series of ReadOny databases, the earlier blog had an interesting comment that read as some people were getting errors of 5120 and others. This got me curious and was in the pending list of solutions in some way.
One of the readers had mailed me saying, they attached a database and the databases came up as ReadOnly. They didn’t know why this happened and when they try to mark the database as ReadWrite, it was giving them an error.
Here are the steps to reproduce the situation. I have the database files in a fileshare. We will try to attach the same using the below command:
USE [master]
GO
CREATE DATABASE [ReadOnlyDB] ON
( FILENAME = N'C:\ReadOnlyDB\ReadOnlyDB.mdf'),
( FILENAME = N'C:\ReadOnlyDB\ReadOnlyDB_log.ldf')
FOR ATTACH
GO
Note: In your case, you can have database files on a different folder.
As soon as the command is executed, we can see in the object explorer the following:
We can see that the database is marked as Read-Only on attach. This was strange. So based on the blog, let us try to make the database as ReadWrite using the following command:
USE [master]
GO
ALTER DATABASE [ReadOnlyDB] SET READ_WRITE WITH NO_WAIT
GO
Now this raised the following error:
Msg 5120, Level 16, State 101, Line 36
Unable to open the physical file “C:\ReadOnlyDB\ReadOnlyDB.mdf”. Operating system error 5: “5(Access is denied.)”.
Msg 5181, Level 16, State 5, Line 36
Could not restart database “ReadOnlyDB”. Reverting to the previous status.
Msg 5069, Level 16, State 1, Line 36
ALTER DATABASE statement failed.
The catch to the error is hidden in the message. It says “Operating system error”. So let us go ahead and detach the DB to change the OS File attributes.
USE [master]
GO
EXEC MASTER.dbo.sp_detach_db @dbname = N'ReadOnlyDB'
GO
Next get to the File system attribute for the database and Log files to check for the ReadOnly attribute. In our example, the mdf file had this attribute enabled.
Please go ahead and uncheck the “Read-only” attribute from the file. That is it. Now attach the database after the change.
USE [master]
GO
CREATE DATABASE [ReadOnlyDB] ON
( FILENAME = N'C:\ReadOnlyDB\ReadOnlyDB.mdf'),
( FILENAME = N'C:\ReadOnlyDB\ReadOnlyDB_log.ldf')
FOR ATTACH
GO
This got us back to normal life as far as our ReadOnly databases is concerned. Hope you learnt something new as I am learning something new almost every single day. Do let me know if you got a chance to learn so much working with ReadOnly databases in the past.
Reference: Pinal Dave (https://blog.sqlauthority.com)
1 Comment. Leave new
Great solution thanks