database attached is read only - sql-server

I used the following the script to attach a database. But the database created is read only.
What modifications should I make in the script to make it read-write. Please help me.
USE [master]
GO
CREATE DATABASE [GemDatabase] ON
( FILENAME = N'E:\Program Files (x86)\ICE Products\ICEConnect200\New Database\GemDatabase.mdf' ),
( FILENAME = N'E:\Program Files (x86)\ICE Products\ICEConnect200\New Database\GemDatabase_log.ldf' )
FOR ATTACH
GO
if not exists (select name from master.sys.databases sd where name = N'GemDatabase' and SUSER_SNAME(sd.owner_sid) = SUSER_SNAME() ) EXEC [GemDatabase].dbo.sp_changedbowner #loginame=N'sa', #map=false
GO

First make sure that the folder in which your .mdf file resides is not read only.
If it is, un-check that option and make sure it reflects to folders and files within that folder.
Once that is done, Open Management Studio, in the Object Explorer right click on the Database which is read only and select Properties. In the Options Menu, check that the Read-Only property is false.

Giving the sql service account 'NT SERVICE\MSSQLSERVER' "Full Control" of the database files
If you have access to the server files/folders you can try this solution that worked for me:
SQL Server 2012 on Windows Server 2008 R2
Right click the database (mdf/ldf) file or folder and select "Properties".
Select "Security" tab and click the "Edit" button.
Click the "Add" button.
Enter the object name to select as 'NT SERVICE\MSSQLSERVER' and click "Check Names" button.
Select the MSSQLSERVER (RDN) and click the "OK" button twice.
Give this service account "Full control" to the file or folder.
Back in SSMS, right click the database and select "Properties".
Under "Options", scroll down to the "State" section and change "Database Read-Only" from "True" to "False".

ALTER DATABASE [DatabaseName] SET READ_WRITE

Make sure the files are writeable (not read-only), and that your user has write permissions on them.
Also, on most recent systems, the Program Files directory is read-only. Try to place the files in another directory.

Open database properties --> options and set Database read-only to False.
Make sure you logged into the SQL Management Studio using Windows Authentication.
Make sure your user has write access to the directory of the mdf and log files.
Did the trick for me...

You need to change permission for your database folder: properties -> security tab -> edit... -> add... -> username "NT Service\MSSQL$SQLEXPRESS" or "NT Service\MSSQLSERVER". Close the windows, open Advanced..., double click the user and set as follows:
Type: Allow
Applies to: This folder, subfolder and files
Basic permissions: all
Make sure the owner is set too.

Another Way which worked for me is:
After dettaching before you attach
-> go to the .mdf file
-> right click & select properties on the file
-> security tab
-> Check Group or usernames:
for your name\account (optional)
and for "NT SERVICE\MSSQLSERVER"(NB)
List item
-> if not there than click on edit button
-> click on add button
and enter\search NT SERVICE\MSSQLSERVER
-> click on OK
-> give full rights
-> apply then ok
then ok again
do this for .ldf file too.
then attach

If SQL Server Service is running as Local System, than make sure that the folder containing databases should have FULL CONTROL PERMISSION for the Local System account.
This worked for me.

You need to go to the new folder properties > security tab, and give permissions to the SQL user that has rights on the DATA folder from the SQL server installation folder.

There are 3 (at least) parts to this.
Part 1: As everyone else suggested...Ensure the folder and containing files are not read only. You will read about a phantom bug in windows where you remove read only from folders and containing items, only to open the properties again and see it still clicked. This is not a bug. Honestly, its a feature. You see back in the early days. The System and Read Only attributes had specific meanings. Now that windows has evolved and uses a different file system these attributes no longer make sense on folders. So they have been "repurposed" as a marker for the OS to identify folders that have special meaning or customisations (and as such contain the desktop.ini file). Folders such as those containing fonts or special icons and customisations etc. So even though this attribute is still turned on, it doesn't affect the files within them. So it can be ignored once you have turned it off the first time.
Part 2: Again, as others have suggested, right click the database, and properties, find options, ensure that the read only property is set to false. You generally wont be able to change this manually anyway unless you are lucky. But before you go searching for magic commands (sql or powershell), take a look at part 3.
Part 3: Check the permissions on the folder. Ensure your SQL Server user has full access to it. In most cases this user for a default installation is either MSSQLSERVER or MSSQLEXPRESS with "NT Service" prefixed. You'll find them in the security\logins section of the database. Open the properties of the folder, go to the security tab, and add that user to the list.
In all 3 cases you may (or may not) have to detach and reattach to see the read only status removed.
If I find a situation where these 3 solutions don't work for me, and I find another alternative, I will add it here in time. Hope this helps.

If you have tried all of this and still no luck, try the detach/attach again.

Here is what worked for me (OS 2016/SQL 2016):
First I ensured that the source and destination SQL had the same version/build.
Log into the server as an administrator:
a. Make sure that the SQL Service account has read, write, execute permissions on the files you want to attach. For me, I noticed that permission-inheritance was disabled, so I re-enabled inheritance and ensured the service account had the correct permissions.
b. Open SSMS on the server and re-run your CREATE DATABASE statement.

just open new query and write this:
alter database [your database] set read_write

The procedure is simple to avoid locking db with read-only atribute:
Detach database
Move the files mdf and ldf to the new location on your computer
Right click on mdf and ldf files (in turn, for each file), Properties, Security Tab, for the ComputerName User check full control. Apply, OK.
Attach database from your new location you put the files

Answer from Varun Rathore is OK but you must consider that starting from Windows Server 2008 R2 and higher the SQLServer service will run under a local virtual account and not anymore under the old well known "NETWORK SERVICE".
Due to this, to switch a newly attached DB to "not read only mode", you must setup permissions on the ldf and mdf files for local machine user line "NT SERVICE\MSSQLSERVER" where MSSQLSERVER would be the service name in a pretty standard installation.
Checkout this https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/configure-windows-service-accounts-and-permissions#VA_Desc for details configuring service permissions

Related

Can't see backup folder in MS SQL Server 2019 [duplicate]

I am trying to run a classic asp project on visual studio and therefore I am trying to restore a database. I cannot seem to find the .bak file when trying to restore it. It wasn't visible in the C-drive. I have looked it up and have seen that it has something to do with permissions. I have tried enabling permissions after properties>security of .bak file to 'Everyone', it did not work. I have also tried NT Service\MSSQLSERVER. Please see the following below.
I had the same issue. I get to know that it was a a permissions issue.
Here are the following steps to solve this problem
Go to Control panel > Administrative Tools > Services double click on the services.
copy the log on account name of sql service as shown in the picture.
Go to your backup folder and right click and select properties.
Follow the steps as shown in picture.
After clicking on edit you will get new window.
Click on add
Paste here the Log on account name of sql service account which you had copied earlier. then Click on check name button.
Select MSSQLSERVER then click ok.
Now you will get your sql server account name in security tab.
Select sql server account name that and in permission box select Allow in all check boxes(I added Full Control) then click apply.
Now you will be able to select and restore your backup file.
You also have to enable permissions to the folder where the file is located. SSMS first needs to browse the folder, then to read the file.
In your case, SQL server tries to access the folder using NT Service\MSSQLSERVER account, so permissions should be granted to that account, no need to give more permissions (to everyone).
Also try below if above doesn't help:
close/open SSMS
move the file from root to some folder and grant permissions to that folder
use TSQL script to restore the database instead of SSMS
you can copy the backup folder in to C:\Users\MSSQL$HCMIS\Desktop sql server users folder.Now it will be accessible
I'm facing simpler issue for sql server standalone 2014 enterprise edition ,installed in my home system . I tried every possibility provided in various article but strangely the issue is with my 2 named instance .
I can restore database on my default instance with query and GUI . I tried changing log-on as account of sql server service for named instance to 'network service' or 'local system' and giving them full control permission to backup holding folder .
In my (and probably a typical/common case): I looked through (and compare with other .bak files) in the windows permission and see nothing wrong.
However - This may be due to that one does not follow to restore from the [device] option first. Even you store the .bak in the right path, it is initially from the [Source]->[Database] check box, until you follow the steps to restore via the [device] option
(In my case the second AdventureWorksDW2020-DAX-Docs was not available until I go thru extra steps to restore it via the [Device] option first.)
The SQLserver need to do internal access right grants to users... etc..(even all the needed Windows properties are in place) –
Reference https://learn.microsoft.com/en-us/sql/samples/adventureworks-install-configure?view=sql-server-ver16&tabs=ssms

An error occurred when attaching the database(s). Click the hyperlink in the Message column for details

i am trying to attach external database named ( HaseebProject.mdf) but every time i got an error
" An error occurred when attaching the database(s). Click the hyperlink in the Message column for details."
What'sthe error is there..?? even there is any error message in message field as shown.
When i click on add button to add database there are two paths in directory for database. i have tried with both but he same error.
Try running SQL Server Management Studio as administrator
All of the answers I've seen so far are possible suggestions of what could be the issue, but it doesn't necessarily help you identify the issue that's preventing you from attaching this database.
The error message you are referring to is actually pointing you to a more specific error message for your case. This more specific error message is located in the Message column of the "Attach Database" window that you've already opened (you may just need to scroll to the right of the "Databases to attach" section and click on the message to see it in its entirety.
I had this problem as well, I did right click on (.mdf and .ldf) the file then on the security tab, click on Edit.
In a new window find the users and set permission to full control. If you can't find users click on:
add button-->advanced-->Find now-->find users
and then click on Ok.
if it doesn't work you can backup from your database and restore it instead of attaching. I have done it and it works.But before restoring make sure that your DB (.mdf and .ldf) shouldn't exist in SQL server database directory before restoring (it's up to your SQL server installation path in my case -->C:\Program Files\Microsoft SQL Server\MSSQL12.SQL2014\MSSQL\DATA) otherwise you will face to an error
Navigate to the directory containing the database and open the
properties for the folder.
Go to the Security tab, Edit permissions, Add User.
In Locations, select the location that is hosting the server.
In object names, Enter NT Service\MSSQL$<Instance-Name> (e.g. NT
Service\MSSQL$MSSQLSERVER).
Set Permissions to full control and save.
This will give your SQL Server instance full permissions for the target directory.
Right-click on the MyDataBase.MDF file
Select Properties -> Go to Security tab -> Select Edit -> Select Add -> Select Advanced -> Select Find Now -> Selecte User Administrator & User Everyone
Set permissions to full control for both
Click OK
Clear MyDataBase_log.LDF file
Copy MyDataBase.MDF file to this location:
(C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA)
Run SQL Server Management Studio as an administrator
Attach MyDataBase.MDF file from this address:
(C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA)
If you already have a database with the same name, delete it before you try to attach the .mdf file. My issue was that they were named the same.
Ryan Harris mentioned looking at the error message, this helped me a lot. So look at that first, you might have a different issue.
SQL message
I had the same issue. The problem was the disk which I was transferring the database file. So if you are copying the database file from one computer to another computer make sure the removable disk is not corrupted. Always try a second removable disk. And also don't forget to run SSMS as administrator.
Use this command to attache db from .mdf file
USE [master]
GO
CREATE DATABASE [SchoolDB] ON
( FILENAME = N'C:\SchoolDB.mdf' )
FOR ATTACH
GO
I had the same issue. After I expanded the error message, I found that it was saying the .MDF file was compressed.
I googled the issue and found this resource that solved my issue.
https://blogs.msdn.microsoft.com/sqlblog/2006/10/02/sql-server-databases-are-not-supported-on-compressed-volumes/
If your error is similar to this:
Create failed for Database 'Compressed_DB'. (Microsoft.SqlServer.Smo)
An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)
The file "E:Compressed_DB.mdf" is compressed but does not reside in a read-only database or filegroup. The file must be decompressed.
CREATE DATABASE failed. Some file names listed could not be created. Check related errors. (Microsoft SQL Server, Error: 5118)
Then you can right click the folder in which the .MDF file resides, click "Properties".
Click "Advanced" in the General tab, and uncheck "Compress contents to save disk space"
This solved the error I was getting, so try it out and attach your .MDF again.
In my case I changed the main database file names so I had to select them again using button in "Current File Path" column.
Resolution:- Just give permission to database folder and attached mdf file then.
check version of the sql server software and the sql software that mdf was created. must be the same versions.

Restoring SQL backup fails - Access is denied

Solved. See my answer (but first see my second edit to the question).
I'm trying to restore a backup for a database from one computer on another - thereby copying the db, but I get this message:
System.Data.SqlClient.SqlError: The operating system returned the
error '5(Access is denied.)' while attempting
'RestoreContainer::ValidateTargetForCreation' on 'c:\Program
Files\Microsoft SQL Server...'. (Microsoft.SqlServer.SmoExtended)
Why is this? I can create new databases, so why not restore? Is it because it's from another computer? (I read that that's actually a usual way to copy a db so this shouldn't be the problem.)
I don't have much experience with this so don't rule out any obvious explanation.
EDIT :
I can 'restore' it using the administrator user account to the administrator's instance of SQL Server (I have two - one for the administrator, and one for the regular account.) but can't do it from either account to the regular user's instance of SQL Server.
EDIT 2 :
It seems that there are already existing files with the backup's files names (even though I changed the existing db's name). I'm working on that now (Trying, still unsuccessfully, to restore to different file names).
The solution was to make sure that the database was created in the MSSQL11.MSSQLSERVER folder (as opposed to the MSSQL10_50.SQLEXPRESS folder). Then SSMS succeeded in 'restoring' the database.
I just got this error with SQLSERVER14 .All I did is just checking the "Relocate all files to folder" checkbox in files tab of the restoration wizard.
The database got restored successfully.
Faced the similar problem. windows security is preventing to Restore the DB to 'Target' location. Fixing security settings can resolve this issue.
Right click on the Target folder-> Properties -> Security -> Select appropriate user and then Edit the permissions ( I have given Full Access to the user). Hope this would fix the problem.
When I got this error message my .bak file was located on my desktop (e.g."C:\Users\[username]\Desktop\database.bak").
When I moved the .bak file to my C drive instead the restore succeeded.

mssql '5 (Access is denied.)' error during restoring database

I want to restore a database from a file (Tasks → Restore → Database; after I select from device and select file) via SQL Server Management Studio.
After that, I get this error:
The operating system returned the error '5(Access is denied.)' while attempting
'RestoreContainer::ValidateTargetForCreation' on 'E:\Program Files\Microsoft SQL
Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\XXXXXX.mdf'.
Msg 3156, Level 16, State 8, Server XXXX, Line 2
How do I fix this problem? Is it a security error?
I recently had this problem. The fix for me was to go to the Files page of the Restore Database dialog and check "Relocate all files to folder".
The account that sql server is running under does not have access to the location where you have the backup file or are trying to restore the database to. You can use SQL Server Configuration Manager to find which account is used to run the SQL Server instance, and then make sure that account has full control over the .BAK file and the folder where the MDF will be restored to.
Well, In my case the solution was quite simple and straight.
I had to change just the value of log On As value.
Steps to Resolve-
Open Sql Server Configuration manager
Right click on SQL Server (MSSQLSERVER)
Go to Properties
change log On As value to LocalSystem
Hoping this will help you too :)
I just ran into this same problem but had a different fix. Essentially I had both SQL Server and SQL Server Express installed on my computer. This wouldn't work when I attempted to restore to SQL Express, but worked correctly when I restored it to SQL Server.
A good solution that can work is go to files > and check the reallocate all files
I tried the above scenario and got the same error 5 (access denied). I did a deep dive and found that the file .bak should have access to the SQL service account. If you are not sure, type services.msc in Start -> Run then check for SQL Service logon account.
Then go to the file, right-click and select Security tab in Properties, then edit to add the new user.
Finally then give full permission to it in order to give full access.
Then from SSMS try to restore the backup.
I was getting the same error while trying to restore SQL 2008 R2 backup db in SQL 2012 DB. I guess the error is due to insufficient permissions to place .mdf and .ldf files in C drive. I tried one simple thing then I succeeded in restoring it successfully.
Try this:
In the Restore DB wizard windows, go to Files tab, change the restore destination from C: to some other drive. Then proceed with the regular restore process. It will definitely get restores successfully!
Hope this helps you too. Cheers :)
There are several causes for this error, I got this error because I checked "Reallocate all files to folder" in the Files tab of Restore Database window but the default path did not exist on my local machine. I had the ldf/mdf files in another folder, once I changed that I was able to restore.
The operating system returned the error '5(access denied.)' when restoring database in sql server can be solved by enabling the Relocate all files to folder in the Files options as follows:
I found this, and it worked for me:
CREATE LOGIN BackupRestoreAdmin WITH PASSWORD='$tr0ngP#$$w0rd'
GO
CREATE USER BackupRestoreAdmin FOR LOGIN BackupRestoreAdmin
GO
EXEC sp_addsrvrolemember 'BackupRestoreAdmin', 'dbcreator'
GO
EXEC sp_addrolemember 'db_owner','BackupRestoreAdmin'
GO
In my case I had to check the box in Overwrite the existing database (WITH REPLACE) under Options tab on Restore Database page.
The reason I was getting this error: because there was already an MDF file present for the database and it was not getting overwritten.
Hope this will help someone.
If you're attaching a database, take a look at the "Databases to attach" grid, and specifically in the Owner column after you've specified your .mdf file. Note the account and give Full Permissions to it for both mdf and ldf files.
I had exactly same problem but my fix was different - my company is encrypting all the files on my machines. After decrypting the file MSSQL did not have any issues to accessing and created the DB. Just right click .bak file -> Properties -> Advanced... -> Encrypt contents to secure data.
this happened to me earlier today, i was a member of the local server's admin group and have unimpeded access, or i thought so. I also ticked the "replace" option, even though there is no such DB in the instance.
Found out that there used to be DB of the same name there, and the MDF and LDF files are still physically located at the data and log folders of the server, but the actual metadata is missing in the sys.databases. the service account of SQL server also can't ovewrwrite the existing files. Found out also that the files' owner is "unknown", i had to change ownership, to the 2 files above so that it is now owned by the local server's admin group, then renamed it.
Then finally, it worked.
The account does not have access to the location for backup file.
Take the following steps to access the SQL Server Configuration Manager via Computer Manager easily
Click the Windows key + R to open the Run window.
Type compmgmt.msc in the Open: box.
Click OK.
Expand Services and Applications.
Expand SQL Server Configuration Manager.
Change User Account in Log On As tab .
Now you can Restore Data Base easily
The fix for me was to go into Options when trying to Restore the database and change the path to the new path.
Here is the screenshot
I encountered the same problem, but my setup is a bit different.
I run my database in a linux docker container
sqlserver management tool in Windows.
What I did was:
sudo docker exec -u root -it sqlserver /bin/bash
This enters the docker container as a root user.
Then:
chmod 777 /path/to/file.bak
777 gives read, write & execute permissions to the file for any group, user

SQL Server 2008 database copy - file permissions

For SQL Server 2008 Developer Edition on Vista 64 bit:
I tried copying a database using a Vista admin account using the attach/detach method and it failed due to a file permission error so I gave the user that sql services are running as write and modify to the directory. The copy didn't work. I then gave it full control. The copy worked.
Does that make sense?
If I revoke full control from the user, will that cause problems?
The weird thing is that in an existing working database with files in a different directory, there are no special permissions on the directory and files for the database, so why does a copy require full control?
When you detach a DB, the MDF/LDF files may be set with more restricted perms than you expect, like exclusive to the principal that did the detach - maybe the SQL Server service account or the domain account of the user that performed the detach. I have in the past had to manually add back permissions on the files' Properties > Security tab for other users, or else the files act as if they are locked. See also http://www.onupdatecascade.com/2009/07/sql-server-locks-mdf-and-ldf-files-upon.html
also: http://msdn.microsoft.com/en-us/library/ms189128.aspx
( thanks GrumpyOldDBA )
If the server and/or data you are working on does not require those restrictive permissions to be set, you can set a startup flag in SQL Server that will override this function. I understand what Microsoft is going for with this - they assume if you detach a DB they don't want just anyone to walk away with the file; however, I think keeping a good hacker from doing that is easier said than done, and encrypting the DB is the best method for safeguarding data.
Anyway, there is a "Trace Flag 1802" which is oddly named, since it's nothing to do with tracing. You'll want to add it to your SQL startup in SQL Configuration Manager if you want to keep this behavior.
https://support.microsoft.com/en-us/kb/922804
I myself had the same issue and found the answer in StackExchange:
https://dba.stackexchange.com/a/77683/11001

Resources