I am using SQL Server 2008 developer edition. I was trying to attach the AdventureWorks2008 database.
When I tried to attach, I received an «access is denied» error. According to the event log, it came from the O/S:
Open failed: Could not open file D:ProjectDataAdventureWorksAdventureWorksLT2008_Data.mdf for file number 0. OS error: 5(Access is denied.).
I thought «NTFS problem», but System (and I) have modify access to both files.
I found that I can successfully attach the database if I log in as sa, but my user account won’t work.
I am a member of the local administrators group on my machine, and I am in the sysadmins role in SQL Server instance.
Any idea why I had to be logged in as sa?
Rob
45.2k24 gold badges122 silver badges150 bronze badges
asked Feb 24, 2010 at 23:19
4
Run SQL Server Management Studio as an Administrator. (right click-> run as administrator) that took care of all the weirdness in my case.
SQL SRV EXPRESS 2008 R2. Windows 7
answered May 22, 2012 at 18:18
MandoMandoMandoMando
5,1854 gold badges28 silver badges35 bronze badges
10
Thank you for all of the comments. Some of you helped to lead me to the answer. Here’s what I found:
It was an NTFS permission problem, and not a SQL problem. Further, it looks kind of bug-like (and it’s repeatable).
The problem:
The account that I was using had full control NTFS permissions to the mdf and ldf files. However, it had those permissions through group membership (the Local Administrators group had permissions, and my account is a member of local admins). (I verified the permissions)
If I try to do the attach, connect to SQL Server as me (where I am in the admins group), it fails with the NTFS problem.
However, if I grant the same file permissions that the local admin group has directly to my Domain Account, then I can attach with no problems.
(oh, and yes, I checked the local groups on this machine, and I verified that my domain account is indeed a member of the local admins group).
So, it looks as though the error occurs because some code (either in SQL Server or Management Studio) checks for the permissions that the user account holds, but it doesn’t go so far as to check group permissions that the user account inherits.
That sounds weird to me, but I can reproduce it over and over again, so I have concluded that it is the answer.
Update: I reported this as a bug: https://connect.microsoft.com/SQLServer/feedback/details/539703/access-denied-attaching-a-database-when-permissions-are-inherited
answered Mar 5, 2010 at 18:04
JMarschJMarsch
21.4k15 gold badges77 silver badges124 bronze badges
13
I’d like to add additional info to the answers that were posted.
Be careful when detaching the database because the windows user you are logged in as becomes the only user with permissions to the .mdf file! The original permissions the .mdf file had which included the user SQLServerMSSQLUser$<computer_name>$<instance_name>
and the Administrators account get overwritten by whichever windows user you are logged in as (not sql server user). Boom, all permissions gone just like that. So do as others have said and right click your .mdf file and double check the permissions.
I ran into this problem because I used SSMS to connect to the database (doesn’t matter which sql server account) and detached the database. After doing that my windows user was the only one that had any permissions to the .mdf file. So later on when I tried to attach the db using the sa account, it threw the «access denied» error.
To keep the original permissions in tact you should take the database offline, then detach, then attach in that order like so:
USE [master]
GO
-- kick all users out of the db
ALTER DATABASE mydb
SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
-- Take the Database Offline
ALTER DATABASE mydb SET OFFLINE WITH
ROLLBACK IMMEDIATE
GO
-- detach the db
EXEC master.dbo.sp_detach_db @dbname = N'mydb'
GO
answered Oct 26, 2011 at 15:48
goku_da_mastergoku_da_master
4,2271 gold badge40 silver badges42 bronze badges
3
Add permission to the folder where your .mdf
file is.
Check this name: NT ServiceMSSQLSERVER
And change the Location
to your server name.
gvlasov
18.4k20 gold badges73 silver badges109 bronze badges
answered Feb 4, 2015 at 16:17
LeonardoLeonardo
2112 silver badges2 bronze badges
1
Run SQL Server Management Studio as an Administrator. (right click-> run as administrator) worked for me with Windows 7 — SQL server 2008 R2
answered Aug 27, 2014 at 9:50
Rolwin CrastaRolwin Crasta
4,2093 gold badges35 silver badges45 bronze badges
2
This problem is caused by UAC (User Account Control), isn’t it? Although your user account is a member of Administrators group, the UAC in Windows 7 doesn’t allow you do do administrator things unless you run programs «as administrator». It is not a real bug in SQL Server or Management Studio or whatever. (Although it could possibly know the problem and ask you for elevated permissions instead of just complaining «error 5».)
answered Jun 16, 2012 at 1:52
Al KeppAl Kepp
5,8012 gold badges27 silver badges48 bronze badges
A SQL2005 database can be attached in this way in Windows 7:
start menu >
all program >
Microsoft sql server 2005 >
sql server management studio >
right click >
run as administrator >
click ok
And then attached database successfully completed.
Artjom B.
61k24 gold badges124 silver badges222 bronze badges
answered Dec 11, 2015 at 14:50
1
When you login as sa
(or any Sql Server account), you’re functioning as the SQL Server service account, when you’re logged in as you, you have the permissions of your account. For some reason you don’t have the appropriate file access but the service account does.
answered Feb 24, 2010 at 23:27
Nick CraverNick Craver
622k136 gold badges1295 silver badges1155 bronze badges
4
I found this solution: Right click on folder where you store your .mdf file —> click Properties —> choose Security tab, click Edit… and give it full control.
Hope this helps!
answered Oct 1, 2016 at 7:40
dnguyendnguyen
1491 gold badge2 silver badges12 bronze badges
it can be fixed easly but radicaly, just go to the folder where you have stored mdf file. select file-> Right click ->click on properties and give full permissions to file for logged in user Security.
answered Sep 19, 2014 at 9:12
Ema.HEma.H
2,8623 gold badges27 silver badges41 bronze badges
The sa
user uses NTFS accounts SQLServerMSSQLUser$<computer_name>$<instance_name>
and SQLServerSQLAgentUser$<computer_name>$<instance_name>
to access the database files. You may want to try adding permissions for one or both these users.
I don’t know if solves your problem since you say you have no problems with the sa
user, but I hope it helps.
answered Mar 5, 2010 at 13:08
djeidotdjeidot
4,5344 gold badges42 silver badges45 bronze badges
0
With me
— Running on window 8
— RIght click SQL Server Manager Studio -> Run with admin. -> attach no problems
answered Feb 27, 2014 at 14:02
WolfWolf
6,3222 gold badges28 silver badges25 bronze badges
Every time I have run into this issue was when attempting to attach a database that is in a different directory from the default database directory that is setup in SQL server.
I would highly recommend that instead of jacking with permissions on various directories and accounts that you simply move your data file into the directory that sql server expects to find it.
answered Apr 8, 2011 at 0:17
NotMeNotMe
87.2k27 gold badges170 silver badges244 bronze badges
4
I just wanted to add this information as well.
http://www.mssqltips.com/sqlservertip/2528/database-attach-failure-in-sql-server-2008-r2/
Solution
You get this error because two different logins did the detach and attach operations. So the files, when detached, were owned by the first login, but the attach failed because the login that was used was not the owner of the mdf and ldf files.
When we detach database files, the owner becomes the person who did the detach command, so to resolve the issue we need to change or add the other login as the owner of the mdf and ldf files.
Right click on the «filename.mdf» file and select properties to check the permissions of the mdf file. Here we can see that only one account has permission to the «filename.mdf» file because that was the account that was used to detach the database.
To resolve this issue, click on the Add… button to add the other login or any other login needed and give the login Full Control. You should do this for the «ldf» file as well. Once you have completed this task click the OK button. (Note for other OS versions you may have an Edit option , click this first and then you will see the Add… option.)
1
For what it’s worth to anyone having the particular variation of this problem that I had:
- SQL Express 2008
- Visual Studio 2010 Premium
Through the context menu of the App_data folder I had created a SQL Express database for debugging purposes. The connection string (used by NHibernate) was as follows:
Server=.SQLExpress;
AttachDbFilename=|DataDirectory|DebugDatabase.mdf;
Database=DebugDatabase;
Trusted_Connection=Yes;
This gave me the same «Access denied» error on the database file. I tried giving various users Full Control to the folder and files, at one point even to «Everyone». Nothing helped, so I removed the added permissions again.
What finally solved it was to open the Server Explorer in Visual Studio, then connect to the MDF, and detach it again. After I’d done that my web app could access the database just fine.
PS. Credits go to this blog post I found while googling this particular problem, triggering the idea to attach/detach the database to solve the issue.
answered Mar 6, 2012 at 21:48
JeroenJeroen
60.1k40 gold badges203 silver badges336 bronze badges
I moved a database mdf from the default Data folder to my asp.net app_data folder and ran into this problem trying to set the database back online.
I compared the security settings of the other file databases in the original location to the moved files and noticed that MSSQL$SQLEXPRESS was not assigned permissions to the files in their new location. I added Full control for «NT SERVICEMSSQL$SQLEXPRESS» (must include that NT SERVICE) and it attached just fine.
It appears that the original Data folder has these permissions and the files inherit it. Move the files and the inheritance breaks of course.
I checked another project’s mdf file which I created directly into its app_data folder. it does not have MSSQL$SQLEXPRESS permissions. Hmmm. I wonder why SQL Express likes one but not the other?
answered Feb 18, 2016 at 5:36
Brad MathewsBrad Mathews
1,5452 gold badges21 silver badges45 bronze badges
1
I got this error as sa.
In my case, database security didn’t matter.
I added everyone full control to the mdf and ldf files,
and attach went fine.
answered Nov 14, 2011 at 15:34
toddmotoddmo
20.2k14 gold badges94 silver badges104 bronze badges
This sounds like NTFS permissions. It usually means your SQL Server service account has read only access to the file (note that SQL Server uses the same service account to access database files regardless of how you log in). Are you sure you didn’t change the folder permissions in between logging in as yourself and logging in as sa? If you detach and try again, does it still have the same problem?
answered Mar 5, 2010 at 12:25
2
I had the same issue when attaching a database. It wasn’t a SQL issue it was an account issue. Go to the panel control/User Account Control Settings/Set to «never notify». Finally,restart the computer and it worked for me.
answered Sep 1, 2011 at 16:42
PaolaPaola
111 bronze badge
I attached the mdf file by right clicking the database and removing the log file
AdventureWorks2012_Data_log.ldf in the wizard . The mdf file was placed in the following location
C:Program FilesMicrosoft SQL ServerMSSQL10.SQLEXPRESSMSSQLDATA
The above method helped me to resolve the issue .
answered Apr 26, 2012 at 15:03
praveenpraveen
12k1 gold badge41 silver badges49 bronze badges
Copy Database to an other folder and attach or Log in SQLServer with «Windows Authentication»
answered May 16, 2015 at 8:23
Chưa biếtChưa biết
9198 silver badges6 bronze badges
I was reading this page and they have an interesting sentence in there:
Caution: Be very selective when adding
users to these roles. For example,
sysadmin maps out to dbo in every
database and is the equivalent of
logging in using the sa account.
Of course, they also have this:
Permissions that are granted to users
and roles and are database specific.
All permissions are cumulative with
the exception of a DENY. A denied
permission at either a user level or
at a role level overrides the same
permission granted via other role
memberships with the exception of the
sysadmin fixed server role. (A
sysadmin retains all permissions, even
if a role they are a member of has a
DENY permission.)
So if you’re a domain admin and in SQL ‘sysadmin’ group, the world should be your crustacean.
Of course, according to Microsoft, you should be taking a quick look at these two pages:
Link to Database Prerequisites
Link to Installing Databases
You’re being naughty and trying to attach them manually Seriously though, do you have all the prerequisites for the AdventureWorks2008 database?
I suspect this is just another Microsoft oddity/edge case, but I could be wrong.
sudhansu63
5,9554 gold badges39 silver badges51 bronze badges
answered Mar 2, 2010 at 13:57
TrevokeTrevoke
4,1051 gold badge27 silver badges48 bronze badges
1
USE [master]
GO
CREATE DATABASE [DataBasename] ON
( FILENAME = N'C:dataDataBasename.mdf' )
FOR ATTACH
GO
change to
FOR ATTACH — > FOR ATTACH_FORCE_REBUILD_LOG
USE [master]
GO
CREATE DATABASE [DataBasename] ON
( FILENAME = N'C:dataDataBasename.mdf' )
FOR ATTACH_FORCE_REBUILD_LOG
GO
answered Sep 3, 2017 at 2:57
0
I was facing same issue in VS 2019. if anyone still facing same issue then please make sure you have/do following things:
- You should have SQL Express installed on your m/c
- Should have SSDT installed in VS (in VS 2019- make sure to check
this component while installing) for previous versions — you
have to add this component externally - Add ‘User Instance = True’ to your connectionstring
- I think its optional — open VS and SQL Express in administrative mode and login as admin to SQL Express
answered Feb 10, 2020 at 17:42
Ashu_90Ashu_90
9047 silver badges8 bronze badges
It is in fact NTFS permissions, and a strange bug in SQL Server. I’m not sure the above bug report is accurate, or may refer to an additional bug.
To resolve this on Windows 7, I ran SQL Server Management Studio normally (not as Administrator). I then attempted to Attach the MDF file. In the process, I used the UI rather than pasting in the path. I noticed that the path was cut off from me. This is because the MS SQL Server (SQLServerMSSQLUser$machinename$SQLEXPRESS) user that the software adds for you does not have permissions to access the folder (in this case a folder deep in my own user folders).
Pasting the path and proceeding results in the above error. So — I gave the MS SQL Server user permissions to read starting from the first directory it was denied from (my user folder). I then immediately cancelled the propagation operation because it can take an eternity, and again applied read permissions to the next subfolder necessary, and let that propagate fully.
Finally, I gave the MS SQL Server user Modify permissions to the .mdf and .ldf files for the db.
I can now Attach to the database files.
answered Apr 8, 2011 at 0:12
Chris MoschiniChris Moschini
36.5k19 gold badges160 silver badges188 bronze badges
If you run sql server 2012 you can get this error by trying to attach an older version of an mdf-file. ex an mdf file from sql server 2008.
answered Oct 18, 2012 at 9:23
1
I have solved the problem by just move the .mdf file that you want to attach to the public folder, in my case I moved it to the users/public folder. Then I attach it from there without any problem. Hope this helps.
answered Aug 26, 2013 at 0:44
For those who could not fix the problem with the other solutions here, the following fix worked for me:
Go to your «DATA» folder in your SQL Server installation, right click, properties, security tab, and add full control permissions for the «NETWORK SERVICE» user.
(The above link is for SQL 2005, but this fixed a SQL 2008 R2 installation for me).
Some additional info: This problem showed up for me after replacing a secondary hard drive (which the SQL installation was on). I copied all the files, and restored the original drive letter to the new hard disk. However, the security permissions were not copied over. I think next time I will use a better method of copying data.
answered Dec 10, 2013 at 20:15
marknuzzmarknuzz
2,7881 gold badge25 silver badges29 bronze badges
In my case what solved the problem was the folowing:
USE [master]
GO
CREATE DATABASE [AdventureWorks2008R2] ON
( FILENAME = 'C:Program FilesMicrosfot SQL ServerMSSQL10_50.SQLEXPRESSMSSQLDATAAdventureWors2008R2_Data.mdf')
FOR ATTACH_REBUILD_LOG
answered Feb 21, 2015 at 14:13
Nick_Nick_
111 silver badge4 bronze badges
I’ve had the same issue when re-attaching database after detaching it and moving ldf and mdf files from drive C to F.
In order to fix it I had to add OWNER RIGHTS principal to both files and gave it full control over them in the Security tab of the Properties dialog.
answered Nov 30, 2015 at 14:17
I am starting to learn SQL and I have a book that provides a database to work on. These files below are in the directory but the problem is that when I run the query, it gives me this error:
Msg 5120, Level 16, State 101, Line 1 Unable to open the physical file
«C:MurachSQL Server 2008DatabasesAP.mdf». Operating system error
5: «5(Access is denied.)».
CREATE DATABASE AP
ON PRIMARY (FILENAME = 'C:MurachSQL Server 2008DatabasesAP.mdf')
LOG ON (FILENAME = 'C:MurachSQL Server 2008DatabasesAP_log.ldf')
FOR ATTACH
GO
In the book the author says it should work, but it is not working in my case. I searched but I do not know exactly what the problem is, so I posted this question.
MAbraham1
1,7174 gold badges28 silver badges45 bronze badges
asked Aug 17, 2013 at 8:30
1
SQL Server database engine service account must have permissions to read/write in the new folder.
Check out this
To fix, I did the following:
Added the Administrators Group to the file security permissions with
full control for the Data file (S:) and the Log File (T:).Attached the database and it works fine.
answered Aug 17, 2013 at 8:37
Rahul TripathiRahul Tripathi
167k31 gold badges277 silver badges331 bronze badges
12
An old post, but here is a step by step that worked for SQL Server 2014 running under windows 7:
- Control Panel ->
- System and Security ->
- Administrative Tools ->
- Services ->
- Double Click SQL Server (SQLEXPRESS) -> right click, Properties
- Select Log On Tab
- Select «Local System Account» (the default was some obtuse Windows System account)
- -> OK
- right click, Stop
- right click, Start
Voilá !
I think setting the logon account may have been an option in the installation, but if so it was not the default, and was easy to miss if you were not already aware of this issue.
answered Feb 17, 2016 at 18:38
10
To get around the access denied issue, I started SSMS as administrator and that allowed me to attach a database from my local drive. The database was created in another SQL and windows instance.
answered Feb 23, 2015 at 11:13
JayKayOf4JayKayOf4
1,2021 gold badge12 silver badges15 bronze badges
4
This is Windows related issue where SQL Server does not have the appropriate permission to the folder that contains .bak file and hence this error.
The easiest work around is to copy your .bak file to default SQL backup location which has all the necessary permissions. You do not need to fiddle with anything else. In SQL SERVER 2012, this location is
D:Program FilesMicrosoft SQL ServerMSSQL11.MSSQLSERVERMSSQLBackup (SQL 2012)
C:Program FilesMicrosoft SQL ServerMSSQL12.MSSQLSERVERMSSQLBackup (SQL 2014)
C:Program FilesMicrosoft SQL ServerMSSQL13.SQLEXPRESSMSSQLBackup (SQL 2016)
answered Oct 9, 2014 at 8:25
TheTechGuyTheTechGuy
16.4k16 gold badges114 silver badges135 bronze badges
6
I had this problem. Just run SQL Server as administrator
Adrian Mole
49.5k155 gold badges49 silver badges79 bronze badges
answered Jul 5, 2017 at 0:55
3
Yes,It’s right.The first you should find out your service account of sqlserver,you can see it in Task Manager when you press ctrl+alt+delete at the same time;Then,you must give the read/write privilege of «C:MurachSQL Server 2008Databases» to the service account.
answered Aug 17, 2013 at 8:48
TimTim
1491 silver badge9 bronze badges
0
I solve this problem by adding Full control
permission for both .mdf
and .ldf
files for Users
group.
answered Dec 2, 2016 at 15:26
1
The problem is due to lack of permissions for SQL Server to access the mdf & ldf files. All these procedures will work :
- you can directly change the MSSQLSERVER service startup user account, with the user account who have better privileges on the files. Then try to attach the database.
- Or you can assign the user to the file in security tab of the mdf & ldf files properties with read and and write privileges checked.
- Startup with windows administrator account, and open SQL Server with run as administrator option and try to login with windows authentication and now try to attach the database.
Manu
4,3746 gold badges43 silver badges77 bronze badges
answered Mar 13, 2015 at 12:12
For me it was solved in the following way with SQL Server Management studio
-Log in as admin (I logged in as windows authentication)
-Attach the mdf file (right click Database | attach | Add )
-Log out as admin
-Log in as normal user
answered May 23, 2016 at 13:03
0
The actual server permissions will not matter at this point; all looks ok.
SQL Server itself needs folder permissions.
depending on your version, you can add SERVERNAME$MSSQLSERVER permissions to touch your folder. Othewise, it has to be in the default BACKUP directory (either where you installed it or default to c:programfiles(x)MSSQLBACKUP.
answered Sep 11, 2014 at 19:27
ClaudiaClaudia
511 silver badge1 bronze badge
Even if you do the following steps you COULD get the same error message.
1. login as SA user (SSMS)
2. Edit the file permissions to say "everyone" full access (windows folder)
3. Delete the Log file (Windows Exploring (this was what I had done per advise from some msdn forum)
I still GOT the permission error, but then I noticed that in the Attach screen, the bottom section STILL showed the LOG file, and the error message remained the same.
Hope this helps someone who did the same thing.
answered May 21, 2014 at 0:18
Tom StickelTom Stickel
19.5k6 gold badges111 silver badges113 bronze badges
It means the SSMS login user does not have permission on the .mdf file. This is how it has worked for me:
I had opened the SSMS (Run as administrator) and login as an administrator user, database right-click attach, click add, select the .mdf file, click Ok. Done.
answered Jul 15, 2020 at 22:44
GoldfishGoldfish
5845 silver badges11 bronze badges
I had this issue when I try to backup a database.
System.Data.SqlClient.SqlError:
Cannot open backup device 'C:xxxxx.bak'.
Operating system error 5 (Access is denied.). (Microsoft.SqlServer.Smo)
When I had this issue I thought that the user which I’m connecting to database don’t have rights to access to the backup location. I gave full control to that user but nothing changed. This is because the service for SQL Server is running with another user.
At this point you may choose changing user of the service to local system account or add access rights for the current user of the service.
I choose the 2nd one.
After that change backup succeeded.
answered May 20, 2022 at 9:47
Ozan BAYRAMOzan BAYRAM
2,6871 gold badge27 silver badges34 bronze badges
1
Very Simple Solution.
- Login with System admin
- copy your mdf and ldf files in «C:Program Files (x86)Microsoft SQL ServerMSSQL11.MSSQLSERVERMSSQLDATA» Where all other data file recides.
- Now attach from there it will work
Draken
3,13413 gold badges33 silver badges53 bronze badges
answered Sep 20, 2016 at 10:19
1
I used Entity framework in my application and had this problem,I seted any permission in folders and windows services and not work,
after that I start my application as administrator (right click in exe file and select «run as admin») and that works fine.
answered Jul 17, 2017 at 7:45
Ali YousefiAli Yousefi
2,3552 gold badges32 silver badges47 bronze badges
If you get this error on an .MDF
file in the APP_DATA
folder (or where ever you put it) for a Visual Studio project, the way I did it was to simply copy permissions from the existing DATA
folder here (I’m using SQL Express 2014 to support an older app):
C:Program FilesMicrosoft SQL ServerMSSQL12.SQLEXPRESS2014MSSQLDATA
(note: your actual install path my vary — especially if your instance name is different)
Double click on theDATA
folder first as administrator to make sure you have access, then open the properties on the folder and mimic the same for the APP_DATA
folder. In my case the missing user was MSSQL$SQLEXPRESS2014
(because I named the instance SQLEXPRESS2014
— yours may be different). That also happens to be the SQL Server service username.
answered Jan 24, 2019 at 1:37
James WilkinsJames Wilkins
6,7252 gold badges47 silver badges73 bronze badges
For some reason, setting all the correct permissions did not help in my case. I had a file db.bak
that I was not able to restore due to the 5(Access is denied.)
error. The file was placed in the same folder as several other backup files and all the permissions were identical to other files. I was able to restore all the other files except this db.bak
file. I even tried to change the SQL Server service log on user — still the same result. I’ve tried copying the file with no effect.
Then I attempted to just create an identical file by executing
type db.bak > db2.bak
instead of copying the file. And voila it worked! db2.bak
restored successfully.
I suspect that some other problems with reading the backup file may be erroniously reported as 5(Access is denied.)
by MS SQL.
answered Nov 27, 2019 at 8:49
ps_ttfps_ttf
1,0967 silver badges15 bronze badges
In linux, I went to /var/opt/mssql/data/
folder and opened a terminal with sudo
then, changed my *.mdf and *.ldf file permissions as below in which you replace yourDB
with your Database file name and myUser
to currently logged username:
chmod 755 yourDB.mdf
chown myUser yourDB.mdf
chmod 755 yourDB.ldf
chown myUser yourDB.ldf
After that, it was reconnected without any issue.
answered Jan 8, 2020 at 8:07
If the database you are trying to attach is compressed it may show error message.
First you have to decompress the file. For that go to properties of mdf/ldf file >> then «Advanced» >> Uncheck «Compress Contents to save disk space» >> Press «Apply».
After that give it a try.
Dharman♦
30.4k22 gold badges84 silver badges132 bronze badges
answered May 20, 2021 at 19:47
1
- Run SQL Server management studio as Administrator
- Log in as Windows user
- Remove log file if you have only MDF file (haven’t log file)
With 3 items in the above checklist, you will remove almost problems related with attach database task.
answered May 22, 2021 at 5:17
If you’re using Storage Gateway — SMB (S3)
Do this from the management studio
-
EXEC xp_cmdshell ‘net use X: 100.155.16.6mystoragegatewayfolder xxmysuperpassxx /user:sgw-445577smbguest /persistent:yes /y’
-
EXEC XP_CMDSHELL ‘Dir X:’ (this should show you the Directory info, serial no etc)
-
Mount the drive (This PC — > Mount network drive, using the same info above)
Test run a backup job using scheduled backup, this will force to use the sql server agent and you can see where it’s writing and whats the issue if any.
answered Aug 9, 2022 at 4:51
I’m trying to execute the following script in SQL Server Management Studio:
USE [master]
GO
CREATE DATABASE [test1] ON PRIMARY (
NAME = N'test1',
FILENAME =
N'C:Program FilesMicrosoft SQL ServerMSSQL10.SQLEXPRESSMSSQLDATAtest1.mdf',
SIZE = 70656KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB)
LOG ON (
NAME = N'test1_log',
FILENAME =
N'C:Program FilesMicrosoft SQL ServerMSSQL10.SQLEXPRESSMSSQLDATAtest1_log.ldf',
SIZE = 164672KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
But I’m getting the error:
Msg 5123, Level 16, State 1, Line 2
CREATE FILE encountered operating system error 5 (Access is denied.)
while attempting to open or create the physical file
‘C:Program FilesMicrosoft SQL ServerMSSQL10.SQLEXPRESSMSSQLDATAtest1.mdf’.Msg 1802, Level 16, State 4, Line 2
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
Already have all role permissions for my user, any ideas on what’s wrong?
Здравствуйте!
Суть проблемы: в проекте в Visual Studio 2008 был файл mdf, добавленный через Проект>Добавить компонент. Все прекрасно работало, пока я не решил открыть этот файл в SQL Server Management Studio, присоединив его к SQL Server 2008. Во время добавления возникла
ошибка:
TITLE: Microsoft SQL Server Management Studio ------------------------------ Attach database failed for Server 'NAMESQLEXPRESS'. (Microsoft.SqlServer.Smo) For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.50.1600.1+((KJ_RTM).100402-1540+)&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Attach+database+Server&LinkId=20476 ------------------------------ ADDITIONAL INFORMATION: An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo) ------------------------------ Unable to open the physical file "D:Database1.mdf". Operating system error 5: "5(Отказано в доступе.)". (Microsoft SQL Server, Error: 5120) For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.50.1600&EvtSrc=MSSQLServer&EvtID=5120&LinkId=20476 ------------------------------ BUTTONS: OK ------------------------------
«Отказано в доступе»-это, я так понимаю, связано с доступом к файлу? Но права у него обычного пользователя, не администратора. Такая же ошибка возникала и при попытке добавить учебную базу данных Борей.
Возвращаюсь обратно в Visual Studio. Там кстати, этот файл прекрасно открывается через «Обозреватель серверов». Открываю свой проект с mdf файлом, нажимаю F5 и получаю ошибку:
Забыл сказать, что в SQL Server Management Studio я хотел открыть не файл из проекта, а его копию, перемещенную в другую папку. И получается, что после первой ошибки, приведенной в посте, не получается подключиться уже и к оригинальному файлу из проекта.
После всего этого, я удалил mdf файл из проекта и все компоненты которые были с ним связаны, думал, что это поможет. Но нет, при попытке добавить этот файл вновь возникает ошибка:
При этом, через «Обозреватель серверов» файл открывается без проблем.
Спасибо за помощь, очень не хотелось бы потерять эту базу данных.
Я хочу восстановить базу данных из файла (задачи->восстановить->база данных; после выбора из устройства и выберите файл) через SQL server management studio.
после этого, я получаю эту ошибку:
операционная система вернула ошибку ‘ 5(Доступ запрещен.) при попытке
‘RestoreContainer:: ValidateTargetForCreation’ on ‘E:Program файлыMicrosoft SQL
Иметь значение mssql10 сервер.ИМЯ MSSQLSERVERMSSQL ДАННЫХДАННЫЕХХХХХХ.МДФ».
Msg 3156, Уровень 16, Состояние 8, сервер XXXX, Строка 2
Как исправить эту проблему? Это ошибка безопасности?
12 ответов
учетная запись, под которой работает sql server, не имеет доступа к местоположению, в котором находится файл резервной копии, или пытается восстановить базу данных. Вы можете использовать диспетчер конфигурации SQL Server найти, какая учетная запись используется для запуска экземпляра SQL Server, а затем убедитесь, что учетная запись имеет полный контроль над .Файл BAK и папка, в которую будет восстановлен MDF.
У меня недавно была эта проблема. Исправление для меня состояло в том, чтобы перейти на страницу файлов диалогового окна восстановления базы данных и проверить «переместить все файлы в папку».
134
автор: Jamie Humphries
Ну, в моем случае решение было довольно простым и прямым.
мне пришлось изменить только значение log On As
значение.
действия разрешения-
- открыть
Sql Server Configuration manager
- право
click on SQL Server (MSSQLSERVER
) - на
Properties
- изменить
log On As
значениеLocalSystem
надеюсь, что это поможет вам тоже:)
Я просто столкнулся с этой же проблемой, но другим исправить. По сути, на моем компьютере были установлены SQL Server и SQL Server Express. Это не сработает, когда я попытаюсь восстановить SQL Express, но работал правильно, когда я восстановил его на SQL Server.
Я нашел это, и это сработало для меня:
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
Если вы присоединяете базу данных, посмотрите на сетку «базы данных для присоединения» и, в частности, в столбце владелец после того, как вы указали свой .файл mdf. Обратите внимание на учетную запись и дайте ей полные разрешения для файлов mdf и ldf.
Я попробовал приведенный выше сценарий и получил ту же ошибку 5 (доступ запрещен). Я глубоко нырнул и обнаружил, что файл .бак должен иметь доступ к учетной записи службы SQL. Если вы не уверены, введите services.msc в меню Пуск — > Выполнить, затем проверьте учетную запись входа в службу SQL.
затем перейдите к файлу, щелкните правой кнопкой мыши и выберите вкладку Безопасность в свойствах, затем отредактируйте, чтобы добавить нового пользователя.
наконец, затем дать полное разрешение на него, чтобы дать полный доступ.
затем из SSMS попробуйте восстановить резервную копию.
Я получал ту же ошибку при попытке восстановить SQL 2008 R2 backup db в SQL 2012 DB. Я предполагаю, что ошибка связана с недостаточными разрешениями для размещения .MDF и. файлы ldf на диске C. Я попробовал одну простую вещь, затем мне удалось успешно восстановить ее.
попробуйте это:
в окне мастера восстановления БД перейдите на вкладку файлы, измените назначение восстановления С C: на другой диск. Затем продолжайте обычный процесс восстановления. Он обязательно получит восстанавливается успешно!
надеюсь, это вам тоже поможет. Ура
в моем случае мне пришлось поставить галочку в Overwrite the existing database (WITH REPLACE)
под Options
tab on Restore Database
страница.
надеюсь, это поможет кому-то.
У меня была точно такая же проблема, но мое исправление было другим — моя компания шифрует все файлы на моих машинах. После расшифровки файла MSSQL не возникло никаких проблем с доступом и создана БД. Просто щелкните правой кнопкой мыши .файл bak ->свойства ->дополнительно… ->шифровать содержимое для защиты данных.
0
автор: Radoslaw Jurewicz
Это случилось со мной ранее сегодня, я был членом группы администратора локального сервера и имел беспрепятственный доступ, или я так думал. Я также отметил опцию «заменить», хотя в экземпляре нет такой БД.
выяснил, что раньше там была БД с тем же именем, а файлы MDF и LDF по-прежнему физически расположены в папках данных и журналов сервера, но фактические метаданные отсутствуют в sys.база данных. учетная запись службы SQL server также не может ovewrwrite существующие файлы. Узнал также, что владелец файлов «неизвестен», мне пришлось сменить владельца на 2 файла выше, чтобы теперь он принадлежал группе администраторов локального сервера, а затем переименовал его.
затем, наконец, это сработало.
Я получил эту ошибку, потому что я проверил «перераспределить все файлы в папку» на вкладке «файлы» окна «восстановить базу данных», но путь по умолчанию не существовал на моей локальной машине. У меня были файлы ldf/mdf в другой папке, как только я изменил, что я смог восстановить.