This blog is about another common error reported by many DBA to me. He faced error related to create file in OS.
Here is the text of the message.
CREATE FILE encountered operating system error 5(Access is denied.) while attempting to open or create the physical file ‘C:\Program Files\Microsoft SQL Server\MSSQL14.SQL2017\MSSQL\DATA\DetachTest.mdf’. (Microsoft SQL Server, Error: 5123)
Important piece in above error message “operating system error 5(Access is denied.)”. From that it is clear that its due to permission issue with the file.
Why this happens?
Whenever a database is detached, the permission of the database files is modified. If any SQL Login has detached the database, then permissions are given to SQL Server Service account. If any Windows account has detached the database, then the permission is given to the account who has detached itself.
To explain the real cause, I decided to reproduce the error. I created a database called DetachTest. A SQL Service account was set to CONTOSO\SQLService. Now, I logged into the server via SSMS with login CONTOSO\syadmin.
Then I detached the database and here are the permissions. You can view them by going to the file > properties and security tab.
Now, I logged in as “sa” account, which is a SQL Login. As I explained earlier, SQL Server would try to use a service account to read the file. As you can expect, the file is not readable by any account other than CONTOSO\sysadmin.
By reading the blog so far, you must have got a clue about what needs to be done to avoid “Access is denied” error. If not, then here are the steps.
- Right-click on the file which is mentioned in the error message and go to properties.
- In the Properties dialog box, go to Security tab.
- In the Select Group or user names box (which has sysadmin in above image). Click the Edit button and enter the name you used to login to SQL Server. If its windows account, then use that account else use service account.
- Click Check Names and verify that the name you are specifying does exist as SQL Server login.
- Click OK.
- In the Group or User Names box, select the user name you selected in the above step and give full control permission to the user. Click OK.
Now you are all set to attach database files by using the SQL Server authentication or Windows authentication.
Reference: Pinal Dave (https://blog.sqlauthority.com)