Sql server management studio ошибка операционной системы

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's user avatar

MAbraham1

1,7174 gold badges28 silver badges45 bronze badges

asked Aug 17, 2013 at 8:30

dijai jijfs's user avatar

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.

enter image description here

enter image description here

Jeremy Thompson's user avatar

answered Aug 17, 2013 at 8:37

Rahul Tripathi's user avatar

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

MickeyfAgain_BeforeExitOfSO's user avatar

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

JayKayOf4's user avatar

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

TheTechGuy's user avatar

TheTechGuyTheTechGuy

16.4k16 gold badges114 silver badges135 bronze badges

6

I had this problem. Just run SQL Server as administrator

Adrian Mole's user avatar

Adrian Mole

49.5k155 gold badges49 silver badges79 bronze badges

answered Jul 5, 2017 at 0:55

Aref Bozorgmehr's user avatar

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

Tim's user avatar

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.

Rahul Tripathi's user avatar

answered Dec 2, 2016 at 15:26

Sayed Abolfazl Fatemi's user avatar

1

The problem is due to lack of permissions for SQL Server to access the mdf & ldf files. All these procedures will work :

  1. 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.
  2. 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.
  3. 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's user avatar

Manu

4,3746 gold badges43 silver badges77 bronze badges

answered Mar 13, 2015 at 12:12

Chandra Sekhar's user avatar

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

RotatingWheel's user avatar

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

Claudia's user avatar

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 Stickel's user avatar

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

Goldfish's user avatar

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.

enter image description here

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.

enter image description here

After that change backup succeeded.

answered May 20, 2022 at 9:47

Ozan BAYRAM's user avatar

Ozan BAYRAMOzan BAYRAM

2,6871 gold badge27 silver badges34 bronze badges

1

Very Simple Solution.

  1. Login with System admin
  2. copy your mdf and ldf files in «C:Program Files (x86)Microsoft SQL ServerMSSQL11.MSSQLSERVERMSSQLDATA» Where all other data file recides.
  3. Now attach from there it will work

Draken's user avatar

Draken

3,13413 gold badges33 silver badges53 bronze badges

answered Sep 20, 2016 at 10:19

AmitykSharma's user avatar

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 Yousefi's user avatar

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 Wilkins's user avatar

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_ttf's user avatar

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

muhammad tayyab's user avatar

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's user avatar

Dharman

30.4k22 gold badges84 silver badges132 bronze badges

answered May 20, 2021 at 19:47

Eldhose p k's user avatar

1

  1. Run SQL Server management studio as Administrator
  2. Log in as Windows user
  3. Remove log file if you have only MDF file (haven’t log file)

enter image description here

With 3 items in the above checklist, you will remove almost problems related with attach database task.

answered May 22, 2021 at 5:17

Raphaël Colantonio's user avatar

If you’re using Storage Gateway — SMB (S3)
Do this from the management studio

  1. EXEC xp_cmdshell ‘net use X: 100.155.16.6mystoragegatewayfolder xxmysuperpassxx /user:sgw-445577smbguest /persistent:yes /y’

  2. EXEC XP_CMDSHELL ‘Dir X:’ (this should show you the Directory info, serial no etc)

  3. 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

Impermanence's user avatar

I have a database file .mdf from MS SQL EXPRESS in folder:

C:Program FilesMicrosoft SQL ServerMSSQL10.SQLEXPRESSMSSQLDATA

I would like to attach it to MS 2008 R2 (MSSQL10_50.MSSQLSERVER) but using Server Management Studio I receive the following error:

CREATE FILE encountered operating system error 5(failed to retrieve text for this error. Reason: 15105) while attempting to open or create the physical file

Do you have any idea how to solve it?

asked Jun 24, 2012 at 15:07

GibboK's user avatar

GibboKGibboK

70.3k139 gold badges423 silver badges648 bronze badges

3

I was able to solve the problem running MS SQL Management Studio as ADMINISTRATOR.

answered Jun 24, 2012 at 15:11

GibboK's user avatar

GibboKGibboK

70.3k139 gold badges423 silver badges648 bronze badges

3

It’s a Windows permissions issue. If you connected to your server using Windows Authentication then that Windows user needs permissions to the file. If you connected to your server using SQL Server authentication then the SQL Server instance account (MSSQL$, e.g. MSSQL$SQLEXPRESS) needs permissions to the file. The other solutions suggesting logging in as an administrator essentially accomplish the same thing (with a bit of a sledgehammer :).

If the database file is in your SQL Server’s data folder then it should have inherited the user rights for the SQL Server account from that folder so the SQL Server authentication should have worked. I would recommend fixing the SQL Server instance’s account’s rights for that folder. If the data file is somewhere else and the SQL Server account does not have permissions then you will likely encounter other problems later. Again, the better solution is to fix the SS account rights. Unless you are always going to log in as administrator…

answered Jan 31, 2013 at 16:56

user2029904's user avatar

user2029904user2029904

5214 silver badges4 bronze badges

6

Start->Run->services.msc->scroll through the list of services until you find SQL Server->right-click->properties->Log On tab:

Then choose Local System Account and check the Allow service to interact with desktop checkbox.

Restart the service.

Services

answered Feb 27, 2019 at 14:12

TiyebM's user avatar

TiyebMTiyebM

2,6263 gold badges39 silver badges64 bronze badges

Giving admin rights or full control to my database install location solved my problem

answered Jul 8, 2015 at 15:03

sidh4work's user avatar

0

Right Click on File mdf and ldf properties -> security ->full permission

RBT's user avatar

RBT

23k21 gold badges155 silver badges231 bronze badges

answered Jan 20, 2015 at 18:51

Ehsan Gholami's user avatar

I had the same problem. After several tries, I realized that connecting the sql server with windows authentication resolved the issue.

answered Nov 22, 2012 at 16:27

Lamar's user avatar

LamarLamar

1,6094 gold badges23 silver badges48 bronze badges

2

I was getting similar error.

CREATE FILE encountered operating system error **32**(failed to retrieve text for this error. Reason: 15105) while attempting to open or create the physical file

I used the following command to attach the database:

EXEC sp_attach_single_file_db @dbname = 'SPDB',
@physname = 'D:SPDB.mdf'

answered Jun 1, 2013 at 20:30

Brij's user avatar

BrijBrij

11k19 gold badges75 silver badges115 bronze badges

This same problem occurs when the owners of the file have been deleted. When this happens, if you go to the file’s properties, you will see a SID rather than a user name. Take ownership of the file (giving yourself FULL CONTROL). Once that is done you can do whatever you need to do with the file.

I’ve had this work when logging in as the administrator didn’t do the trick.

answered Nov 30, 2012 at 15:00

PseudoToad's user avatar

PseudoToadPseudoToad

1,4841 gold badge16 silver badges34 bronze badges

As other suggested running as administrator will help.

However this only if the windows user is actually an admisnitrator on the machine which sql server runs.

For example when using SSMS from a remote machine it will not help using «run as administartor» if the user is only a administrator on the machine runing SSMS but not on the machine running SQL Server.

answered May 9, 2013 at 19:39

yoel halb's user avatar

yoel halbyoel halb

12k3 gold badges53 silver badges51 bronze badges

1.copy your —.MDF,—.LDF files to pate this location
For 2008 server
C:Program FilesMicrosoft SQL ServerMSSQL10.MSSQLSERVERMSSQLDATA
2.In sql server 2008 use ATTACH and select same location for add

answered May 23, 2013 at 12:49

pradeep's user avatar

pradeeppradeep

1381 silver badge3 bronze badges

I had this issue on Windows 2003 with SQL 2005. I had to take ownership of the files as my Windows user account and I got the database to attache that way.

You have to right click on the file, select Properties, click OK to get past the information screen, click the Advanced button, select your account from the listing of available accounts or groups, apply that change, and Click OK on the Properties screen. Once you have done all that you will be able to manage the file permissions.

I logged into SSMS with Windows Authentication and I was able to attach the database without error.

Cheers!

answered Jan 4, 2014 at 13:19

IryDBA2791's user avatar

If you are already running as an adminstrator, make sure the user you are using has the proper server roles.

  1. Login as sa (if you can)
  2. Expand the Security folder
  3. Expand the Logins Folder
  4. Right click on the user you would like to use
  5. Select Properties
  6. Select Server Roles
  7. Select all the server roles
  8. Click OK
  9. Restart SSMS
  10. Login with the modified user

answered Apr 24, 2013 at 15:14

jnoreiga's user avatar

jnoreigajnoreiga

2,14819 silver badges26 bronze badges

In my case I have got the error when trying to create a databae on a new drive.
To overcome the problem I created a new folder in that drive and set the user properties Security to full control on it(It may be sufficient to set Modify ).
Conclusion:
SET the Drive/Folder Properties Security for users to «Modify».

answered May 13, 2014 at 4:45

Menahem's user avatar

My solution was slightly more complicated. After verifying the user the service was running as, running MSSMS as local and domain administrator, and checking folder permissions, I was still getting this error. My solution?

Folder ownership was still maintained by local account.

Properties > Security > Advanced > Owner > (domain/local user/group SQL services are running as)

This resolved the issue for me.

answered Jul 15, 2014 at 19:22

xkalibur's user avatar

Opening SSMS as Administrator and running as SQL Auth vs Windows Auth did not work.

What worked was to just change my filename to the same location where the LDF and MDF files are located.

alter database MyDB
add file ( name = N'FileStreamName', 
filename = N'D:SQL DatabasesFileStreamSpace' ) 
to filegroup DocumentFiles;

answered Dec 9, 2014 at 9:54

Cameron Castillo's user avatar

Cameron CastilloCameron Castillo

2,85410 gold badges46 silver badges73 bronze badges

I got this error when restoring a database that was backed up on another server. After a long struggle this is what I did

  1. Enabled Instant File Initialization,

  2. Granted permissions (full control) on the folder to the service account and my own windows account,

  3. Restarted the SQL service.
    Database restored after that.

dur's user avatar

dur

14.9k24 gold badges80 silver badges117 bronze badges

answered Dec 1, 2015 at 15:07

Lucian's user avatar

We faced this issue, when the windowsuser detaching the database and windowsuser attaching the database are different. When the windowsuser detaching the database, tried to attach it, it worked fine without issues.

answered May 12, 2017 at 21:10

Venkataraman R's user avatar

Venkataraman RVenkataraman R

11.7k2 gold badges26 silver badges49 bronze badges

Here are the steps:

  1. Right click on the .mdf and .ldf file.
  2. Then select properties.
  3. On the security -> advanced -> permission add the user which

RBT's user avatar

RBT

23k21 gold badges155 silver badges231 bronze badges

answered Aug 25, 2015 at 6:22

ehsan farahmand's user avatar

copy your --.MDF,--.LDF files to pate this location For 2008 server C:Program FilesMicrosoft SQL ServerMSSQL10.MSSQLSERVERMSSQLDATA 2.

In sql server 2008 use ATTACH and select same location for add

The Hungry Dictator's user avatar

answered Aug 21, 2014 at 7:53

Munish Gupta's user avatar

I just decided to create the file in D: instead of C: and everything worked well. windows 7…10 have many issues regarding the sharing and authorization of files and folder..

answered Mar 17, 2018 at 11:10

Sohail's user avatar

In my case, Run as Administrator does not help. I solved the problem by changing the Build-in Account to Local System in Configuration Manager.

answered Nov 3, 2018 at 9:20

NewComer's user avatar

NewComerNewComer

3071 gold badge3 silver badges8 bronze badges

1

Here is what happened in my case.
I was asked to attach files for a database. I was given the file names as follows

  • devdb.mdf and devdb.ldf

I proceeded to attach the files and kept getting the files are in use by another process.

I ran a query against the system view select name, physical_name from sys.master_files; and saw that the exact file names were already in use by another database, thus each time I tried to attach the files, I kept getting the error the files are in use by another process(sql server)

Thus if you are getting such a message, then also query against the system view sys.master_files and see which database may already be using the same name files.
Hereafter you will figure out what to do.

thanks.

answered Dec 11, 2018 at 21:33

sqladmin's user avatar

if you have mount points add the the SQL server service account to volume security accordingly

answered Feb 20, 2019 at 9:58

meto's user avatar

I also face same problem, but i run Sql server run as administrator so now i resolve the error.

answered Oct 12, 2022 at 6:33

Vandit Joshi's user avatar

1

No need to do all this. Just right click on database files and add permission to everyone. That will work for sure.

Paresh Mayani's user avatar

Paresh Mayani

127k71 gold badges239 silver badges295 bronze badges

answered Mar 13, 2014 at 18:49

shroffakshar's user avatar

2

  • Remove From My Forums
  • Question

  •  HI ,

     This is a problem I encountered when I had to detach a database file (type .mdf):

     1) I went to the MS SQL Management Server Studi and detached my database file successfully from a connection called Workhorse.

    2) I needed to place the .mdf database file into a zip file in order to put it on a remote server. I did this using Shared Portal.  This was also successful

    3) However when I tried reattaching the database file, I got this error:

    CREATE FILE encountered operating system error 5A(Access denied.) while attempting to open or create the physical file «CProgram FilesMSSQL ServerMSSQLData<databasename>.mdf’

    Q) The database file and log file (ldf) exist in the correct directory so I don’t know what happened. Can any one help?

     Thanks much

    Tonante

Answers

  • I had same issue on Vista machine. I run «SQL Server Express Management Studio» as «Run as administrator» and it worked. Smile

    • Proposed as answer by

      Tuesday, September 1, 2009 8:56 PM

    • Marked as answer by
      Kalman Toth
      Wednesday, May 28, 2014 12:13 AM
  • I had same issue on Vista machine. I run «SQL Server Express Management Studio» as «Run as administrator» and it worked. Smile

    I was running an Enterprise SQL Server on Win 2008 and ‘Run as Administrator’ fixed the error I was getting.

    • Marked as answer by
      Kalman Toth
      Wednesday, May 28, 2014 12:13 AM
  • Rather then giving permissions to EVERYONE, try running the Management Studio
    as Administrator.

    • Proposed as answer by
      Justin Tolchin
      Tuesday, May 7, 2013 6:59 PM
    • Marked as answer by
      Kalman Toth
      Wednesday, May 28, 2014 12:13 AM

Проблема

При попытке подключить базу данных в Autodesk Data Management Server Console появляется следующее сообщение об ошибке:

Image.png


Autodesk Data Management Server Console ГГГГ

При выполнении команды СОЗДАТЬ ФАЙЛ произошла ошибка операционной системы 5 (доступ запрещен). при попытке открыть или создать физический файл «:Program FilesMicrosoft SQL ServerMSSQL13.AUTODESKVAULTMSSQLDataDb_FilesKnowledgeVaultMaster.mdf».

OK

Среда:

Vault Professional Server можно установить на отдельном компьютере от SQL Server.

Причины:

Права не задаются в файлах и папках SQL Server. Для этого может быть несколько причин.

Решение

Если экземпляр AUTODESKVAULT SQL установлен на компьютере, удаленном от Vault Server, следуйте инструкциям в справочной системе.

Настройка Vault для удаленного SQL

Убедитесь, что учетная запись, которая запускает службу AUTODESKVAULT SQL, имеет разрешение Полный доступ, находится в папке данных SQL и ее содержимом.
Определение учетной записи службы SQL

  1. Нажмите клавиши Windows Start Key + R.
  2. Запустится апплет «Run».

Изображение, добавленное пользователем

  1. Введите Services.msc.
  2. Нажмите «ОК».
  3. Найдите службу SQL Server (AUTODESKVAULT).

Изображение, добавленное пользователем

  1. Учетная запись службы — это значение, отображаемое в поле «Вход в систему как».
  2. Убедитесь, что в учетной записи службы имеется полный доступ к папке данных SQL и ко всем содержащимся в ней файлам.

Изображение, добавленное пользователем

  1. Учетная запись службы — это значение, отображаемое в поле «Вход в систему как».
  2. Убедитесь, что в учетной записи службы имеется полный доступ к папке данных SQL и ко всем содержащимся в ней файлам.

Изображение, добавленное пользователем

См. также:

  • Сообщение «При выполнении команды CREATE FILE произошла ошибка операционной системы 2 (системе не удалось найти указанный файл)…» при попытке подключения базы данных к SQL Server
  • Сообщение «При выполнении команды СОЗДАТЬ ФАЙЛ произошла ошибка операционной системы 32 (процесс не может получить доступ к файлу, так как он используется другим процессом)…» при подключении хранилища с помощью консоли ADMS

Программы

Vault Basic, Vault Professional, Vault Workgroup

Ошибка на ровном месте (но найти решение оказалось очень трудоемким), поэтому решил выложить, авось кому пригодится

Добрый день, коллеги!

В общем, история такая. Есть БД на 1С 8.2, которую я переношу на 1С 8.3, вроде процесс идет. Все ниже перечисленное (алиас БД и прочее — вымышленное или тестовое 🙂

Давеча решил восстановить БД из архива, все просто, но вот застрял на пару дней. У меня была одна тестовая база, и я решил накатить архив на нее. Архив восстановился без проблем, я поработал, потом решил забрать БД домой и проработать детали дома (благо февральские праздники, вообще не представляю, что делать в длинные праздники). Поработал дома, прихожу в офис, копирую БД и делаю «Присоединить» и опля — ошибка:

Сразу подумал на права, назначил все права, полный доступ, Unlocker не помог. Русский сегмент интернета тоже, там сходились на мысли, мол «дай права и все», «проверь под какой учеткой запускается сервисы sql», короче ничего дельного. Пришолось гуглить на забугорных сайтах и вот добрый человек из «клятой» нами «пиндосии» дал норм совет, который я и выкладываю (если кто сможет объяснить лучше я только рад)

1. Проблема была в системной базе TempDB, а имеено типа в ней уже лежит инфа о том, что БД, которую я пытаюсь присоединить уже «присоединена», хотя в списке БД в дереве «Обозревателя объектов» этой БД нет, поэтому попытка «Присоединить» заканчивается fatal error OS код ошибка (32 ). Надо как-то обновить инфу в этомй системной базе.

2. Для начало надо было убедиться в что ошибка именно в этом, скачиваем программу Process Explorer

3. Запускаем

4. На панели инструментов «Find» ищем какие процессы «глумятся» над нашим mdf файлом

5. Видим такую картину

6. Как видно, кроме sqlserver никакого

7. Далее запускаем из командной консоли следующую последовательность команд

1. Старт SQL Server с параметрами “Net Start MSSQL$SQL2014 /mSQLCMD /f /T3608” 
2. Старт SQLCMD с параметрами «SQLCMD –S(local)SQL2014» 
3. Выполним скрипт T-SQL

USE master;
GO
ALTER DATABASE tempdb
MODIFY FILE (NAME = tempdev, FILENAME = 'C:Program FilesMicrosoft SQL ServerMSSQL12.SQL2014MSSQLDATA	empdb.mdf');
GO
ALTER DATABASE tempdb
MODIFY FILE (NAME = templog, FILENAME = 'C:Program FilesMicrosoft SQL ServerMSSQL12.SQL2014MSSQLDATA	empdb.ldf');
GO

4. Стоиим SQL командой “net stop MSSQL$SQL2014

5. Старт SQL.в норм режиме (без параметров)

Возможно, у вас пути выглядят по-другому, у меня все стандартно на C установлена.

И вуаля БД присоединяется без проблем, и можно дальше колдовать над ней. Спасибо аглицким доброжелателям, нехай зря мы их «поливаем» дер….мом.

P.S. может, излишне эмоционально, но реально это помогло, а то все 4 дня магичекого колдовства дома над базой, и бац — на работе не мог обновиться (дело не в коде и сравнить/объединить cf файл, а именно сама инфа, которую не выгрузишь в dt файл (нет, можно выгрузить, но только лет через 100 выгрузится база размером 600 ГБ), так что гоняю базу через sql).

Ну и всех женщин с наступающим международным женским днем!

grillz

0 / 0 / 0

Регистрация: 09.10.2012

Сообщений: 27

1

Ошибка при создании базы

30.01.2013, 13:47. Показов 12465. Ответов 2

Метки нет (Все метки)


Сообщение 1802, уровень 16, состояние 4, строка 1
Ошибка операции CREATE DATABASE. Некоторые из перечисленных имен файлов не были созданы. Проверьте связанные ошибки.
Сообщение 5123, уровень 16, состояние 1, строка 1
Операция CREATE FILE вызвала ошибку операционной системы 5(Отказано в доступе.) при попытке открыть либо создать физический файл «D:Institut_Robu.mdf».
Сам запрос:

MySQL
1
2
3
4
5
create database Institut_
on primary
(name=institute,filename="D:Institut_Robu.mdf")
log on
(name=institute_log,filename="D:Institute_log_.Robu.ldf")

Скрин

Миниатюры

Ошибка при создании базы
 

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

0 / 0 / 0

Регистрация: 09.10.2012

Сообщений: 27

30.01.2013, 22:37

 [ТС]

2

как я разобрался, то нету прав администратора.. хотя непонятно почему. как это решить?

Добавлено через 7 часов 53 минуты
разобрался. закрывайте.

0

asd24

107 / 107 / 5

Регистрация: 28.12.2012

Сообщений: 207

30.01.2013, 22:37

3

Для начала попробуйте выполнить

T-SQL
1
CREATE DATABASE Institut_

Этим вы сможете проверить есть ли у вас права на создание БД
Также вам необходимо глянуть настройки пользователя, под которым работаете.
Security -> Logins -> Выбираете своего пользователя -> ServerRole — sysadmin, public

1

Я
   AzamaT90

15.01.18 — 08:11

Всем привет. Не могу запустить задачу «проверка целостности база данных», должен срабатывать через агент, но даже в ручную не запускается. Выдает ошибку:

Сбой выполнения запроса «DBCC CHECKDB(N’alpha’)  WITH NO_INFOMSGS

» со следующей ошибкой: «Невозможно создать моментальный снимок базы данных из-за ошибки ее запуска.

Операция CREATE FILE вызвала ошибку операционной системы 5(Отказано в доступе.) при попытке открыть либо создать физический файл «G:SQLalpha.mdf:MSSQL_DBCC6».

Не удалось создать моментальный снимок базы данных для проверки в сети. Причина содержится либо в предыдущем сообщении об ошибке, либо в том, что один из используемых дисковых томов не поддерживает разреженные файлы или дополнительные потоки. Производится попытка получить монопольный доступ для запуска проверки вне сети.

Базу данных нельзя заблокировать монопольно для выполнения операции.

Инструкция проверки отменена. База данных не может быть проверена, так как не удалось создать ее моментальный снимок, и база данных или таблица не может быть заблокирована. Более подробно о том, когда возникает данная ситуация и какие существуют обходные пути, см. электронную документацию. См. также предыдущие сообщения об ошибках.». Возможные причины сбоя: проблемы с этим запросом, свойство «ResultSet» установлено неправильно, параметры установлены неправильно или соединение было установлено неправильно.

Права на папку дал все пользователем sql, место на HDD на половину занято.

   DrZombi

1 — 15.01.18 — 08:38

(0) Сервер скуля не может писать, вроде нормально описал, сам скуль. Вопрос то в чем, как правильно читать написанное? :)

   DrZombi

2 — 15.01.18 — 08:42

+ Проверь право доступа к файлику скуля

+ проверь место на скуль сервере.

+ Есть замечательный ресурс по работе с эсКуэлем

http://www.sql.ru/forum/991813/prisoedinenie-fayla-bazy-bez-fayla-loga

И даже там пишут, что автор сам виноват, и не читает логи и сообщения :)

   rs_trade

3 — 15.01.18 — 08:42

(0) вопрос то в чем? в ошибке все же расписано что и почему.

   MrCoffin

4 — 15.01.18 — 10:08

(0) «Права на папку дал все пользователем sql, место на HDD на половину занято.»

Надо не всем, а пользователю из-под которого запущен скуль.

«На половину» — на половину лаптя? В цифрах давай, хотя, подозреваю, что проблема только в пользователе.

  

AzamaT90

5 — 15.01.18 — 10:09

Ошибка была в свойствах файлах баз. Была помечена только чтения. Всем спасибо.

Компьютеры — это как велосипед. Только для нашего сознания. Стив Джобс

ВНИМАНИЕ! Если вы потеряли окно ввода сообщения, нажмите Ctrl-F5 или Ctrl-R или кнопку «Обновить» в браузере.

Тема не обновлялась длительное время, и была помечена как архивная. Добавление сообщений невозможно.
Но вы можете создать новую ветку и вам обязательно ответят!
Каждый час на Волшебном форуме бывает более 2000 человек.

Вопрос:

У меня есть файл базы данных .mdf из MS SQL EXPRESS в папке:

C:Program FilesMicrosoft SQL ServerMSSQL10.SQLEXPRESSMSSQLDATA

Я хотел бы прикрепить его к MS 2008 R2 (MSSQL10_50.MSSQLSERVER), но используя Server Management Studio, я получаю следующую ошибку:

CREATE FILE encountered operating system error 5(failed to retrieve text for this error. Reason: 15105) while attempting to open or create the physical file

У вас есть идеи, как его решить?

Лучший ответ:

Мне удалось решить проблему с запуском MS SQL Management Studio в качестве ADMINISTRATOR.

Ответ №1

Это проблема с разрешениями Windows. Если вы подключились к вашему серверу с помощью проверки подлинности Windows, то пользователю Windows необходимы разрешения для файла. Если вы подключились к вашему серверу с помощью проверки подлинности SQL Server, то учетная запись экземпляра SQL Server (MSSQL $, например MSSQL $SQLEXPRESS) нуждается в разрешениях к файлу. Другие решения, предлагающие войти в систему как администратор, по существу выполняют одно и то же (с куском кувалды:).

Если файл базы данных находится в папке данных SQL Server, он должен унаследовать права пользователя для учетной записи SQL Server из этой папки, чтобы проверка подлинности SQL Server работала. Я бы рекомендовал исправить права учетной записи экземпляра SQL Server для этой папки. Если файл данных находится где-то в другом месте, а учетная запись SQL Server не имеет разрешений, вы, скорее всего, столкнетесь с другими проблемами позже. Опять же, лучшим решением является исправление прав учетной записи SS. Если вы не собираетесь входить в систему как администратор…

Ответ №2

Щелкните правой кнопкой мыши на файле mdf и ldf-свойствах → безопасность → полное разрешение

Ответ №3

Предоставление прав администратора или полного управления моей базой установки базы данных решает мою проблему

Ответ №4

У меня была та же проблема. После нескольких попыток я понял, что подключение сервера sql с проверкой подлинности Windows решило проблему.

Ответ №5

В качестве альтернативы поможет другой предлагаемый запуск под управлением администратора.

Однако это только в том случае, если пользователь Windows фактически является админитратором на машине, на которой выполняется SQL-сервер.

Например, при использовании SSMS с удаленного компьютера это не поможет использовать “запустить как administartor”, если пользователь является только администратором на компьютере, запускающем SSMS, но не на машине, на которой работает SQL Server.

Ответ №6

1. скопируйте ваши файлы -. MDF, -. LDF в pate в этом месте
Для сервера 2008 года
C:Program FilesMicrosoft SQL ServerMSSQL10.MSSQLSERVERMSSQLDATA
2. В SQL Server 2008 используйте ATTACH и выберите то же место для добавления

Ответ №7

Я получал схожую ошибку.

CREATE FILE encountered operating system error **32**(failed to retrieve text for this error. Reason: 15105) while attempting to open or create the physical file

Я использовал следующую команду для присоединения базы данных:

EXEC sp_attach_single_file_db @dbname = 'SPDB',
@physname = 'D:SPDB.mdf'

Ответ №8

У меня была эта проблема в Windows 2003 с SQL 2005. Я должен был взять на себя права на файлы в качестве учетной записи пользователя Windows, и я получил базу данных таким образом.

Вы должны щелкнуть правой кнопкой мыши по файлу, выбрать “Свойства”, нажать “ОК”, чтобы перейти к экрану информации, нажмите кнопку “Дополнительно”, выберите свою учетную запись из списка доступных учетных записей или групп, примените это изменение и нажмите “ОК” на Экран свойств. После того, как вы все это сделаете, вы сможете управлять разрешениями на файлы.

Я вошел в SSMS с Windows Authentication, и я смог подключить базу данных без ошибок.

Ура!

Ответ №9

Эта же проблема возникает, когда владельцы файла были удалены. Когда это произойдет, если вы перейдете к свойствам файла, вы увидите идентификатор SID, а не имя пользователя. Соблюдайте файл (дайте себе ПОЛНЫЙ КОНТРОЛЬ). Как только это будет сделано, вы сможете делать все, что вам нужно с файлом.

У меня была эта работа при входе в систему, поскольку администратор не выполнял трюк.

Ответ №10

Если вы уже работаете как администратор, убедитесь, что пользователь, которого вы используете, имеет правильные роли сервера.

  • Войдите в систему как sa (если можете)
  • Разверните папку “Безопасность”
  • Разверните папку “Логины”
  • Щелкните правой кнопкой мыши пользователя, который вы хотите использовать
  • Выберите “Свойства”
  • Выбор ролей сервера
  • Выберите все роли сервера
  • Нажмите “ОК”
  • Перезапуск SSMS
  • Вход с измененным пользователем

Ответ №11

В моем случае у меня возникла ошибка при попытке создать databae на новом диске.
Чтобы преодолеть эту проблему, я создал новую папку на этом диске и установил для нее полнофункциональные свойства безопасности Security (может быть достаточно установить Modify).
Вывод:
УСТАНОВИТЕ “Безопасность диска/папки” для пользователей “Изменить”.

Ответ №12

Мое решение было несколько сложнее. После проверки пользователя работала служба, выполнявшая MSSMS как локальный и администратор домена, и проверка прав доступа к папке, я все еще получал эту ошибку. Мое решение?

Владение папкой по-прежнему поддерживалось локальной учетной записью.

Свойствa > Безопасность > Дополнительно > Владелец > (службы домена/локального пользователя/группы SQL работают как)

Это разрешило проблему для меня.

Ответ №13

скопируйте файлы --.MDF, --.LDF, чтобы просмотреть это местоположение. Для сервера 2008 C:Program FilesMicrosoft SQL ServerMSSQL10.MSSQLSERVERMSSQLDATA 2.

В sql server 2008 используйте ATTACH и выберите то же местоположение для добавления

Ответ №14

Открытие SSMS в качестве администратора и запуск под управлением SQL Auth vs Windows Auth не работает.

Сработало было просто изменить мое имя файла в том же месте, где расположены файлы LDF и MDF.

alter database MyDB
add file ( name = N'FileStreamName',
filename = N'D:SQL DatabasesFileStreamSpace' )
to filegroup DocumentFiles;

Ответ №15

Вот шаги:

  • Щелкните правой кнопкой мыши файл .mdf и .ldf.
  • Затем выберите свойства.
  • В объявлении security → advanced → добавьте пользователя, который

Ответ №16

Я получил эту ошибку при восстановлении базы данных, которая была скопирована на другой сервер. После долгой борьбы это то, что я сделал

  • Включить мгновенную инициализацию файла,

  • Предоставленные разрешения (полный контроль) в папке для учетной записи службы и моей учетной записи Windows,

  • Перезапуск службы SQL.
    После этого восстановлена ​​база данных.

Ответ №17

Ответ №18

Мы столкнулись с этой проблемой, когда windowsuser, удаляющий базу данных и windowsuser с базой данных, отличается. Когда windowsuser, отсоединив базу данных, попытался прикрепить ее, он работал нормально без проблем.

Ответ №19

Я просто решил создать файл в D: вместо C: и все работало хорошо. Windows 7… 10 имеет много проблем, касающихся совместного использования и авторизации файлов и папок.

Ответ №20

В моем случае Run as Administrator не помогает. Я решил проблему, изменив встроенную учетную запись на локальную систему в Configuration Manager.

Ответ №21

Вот что произошло в моем случае. Меня попросили прикрепить файлы для базы данных. Мне дали имена файлов следующим образом

  • devdb.mdf и devdb.ldf

Я продолжал прикреплять файлы и продолжал получать файлы, используемые другим процессом.

Я выполнил запрос к системному представлению выбора имени, имя_физического из sys.master_files; и увидел, что точные имена файлов уже используются другой базой данных, поэтому каждый раз, когда я пытался прикрепить файлы, я продолжал получать сообщение об ошибке, что файлы используются другим процессом (сервер SQL)

Таким образом, если вы получаете такое сообщение, сделайте запрос к системному представлению sys.master_files и посмотрите, какая база данных уже использует те же файлы имен. В дальнейшем вы разберетесь, что делать.

Благодарю.

Ответ №22

Не нужно делать все это. Просто щелкните правой кнопкой мыши файлы базы данных и добавьте разрешение всем. Это будет работать точно.

By default login failed error message is nothing but a client user connection has been refused by the server due to mismatch of login credentials. First task you might check is to see whether that user has relevant privileges on that SQL Server instance and relevant database too, thats good. Obviously if the necessary prvileges are not been set then you need to fix that issue by granting relevant privileges for that user login.

Althought if that user has relevant grants on database & server if the Server encounters any credential issues for that login then it will prevent in granting the authentication back to SQL Server, the client will get the following error message:

Msg 18456, Level 14, State 1, Server <ServerName>, Line 1
Login failed for user '<Name>'

Ok now what, by looking at the error message you feel like this is non-descriptive to understand the Level & state. By default the Operating System error will show ‘State’ as 1 regardless of nature of the issues in authenticating the login. So to investigate further you need to look at relevant SQL Server instance error log too for more information on Severity & state of this error. You might look into a corresponding entry in log as:

2007-05-17 00:12:00.34 Logon     Error: 18456, Severity: 14, State: 8.
or

2007-05-17 00:12:00.34 Logon     Login failed for user '<user name>'.

As defined above the Severity & State columns on the error are key to find the accurate reflection for the source of the problem. On the above error number 8 for state indicates authentication failure due to password mismatch. Books online refers: By default, user-defined messages of severity lower than 19 are not sent to the Microsoft Windows application log when they occur. User-defined messages of severity lower than 19 therefore do not trigger SQL Server Agent alerts.

Sung Lee, Program Manager in SQL Server Protocols (Dev.team) has outlined further information on Error state description:The common error states and their descriptions are provided in the following table:

ERROR STATE       ERROR DESCRIPTION
------------------------------------------------------------------------------
2 and 5           Invalid userid
6                 Attempt to use a Windows login name with SQL Authentication
7                 Login disabled and password mismatch
8                 Password mismatch
9                 Invalid password
11 and 12         Valid login but server access failure
13                SQL Server service paused
18                Change password required


Well I'm not finished yet, what would you do in case of error:

2007-05-17 00:12:00.34 Logon     Login failed for user '<user name>'.

You can see there is no severity or state level defined from that SQL Server instance’s error log. So the next troubleshooting option is to look at the Event Viewer’s security log [edit because screen shot is missing but you get the

idea, look in the event log for interesting events].

Студворк — интернет-сервис помощи студентам

Добрый день, пытаюсь присоединить базу данных созданную в sql server 2008 r2 в sql server 2008 r2.
Но вылетает ошибка
ЗАГОЛОВОК: Microsoft SQL Server Management Studio
——————————

Действие Присоединить базу данных завершилось неудачно для объекта «Сервер» «DESKTOP-P4T3G98». (Microsoft.SqlServer.Smo)

Чтобы получить справку, щелкните: http://go.microsoft.com/fwlink… nkId=20476

——————————
ДОПОЛНИТЕЛЬНЫЕ СВЕДЕНИЯ:

При выполнении инструкции или пакета Transact-SQL возникло исключение. (Microsoft.SqlServer.ConnectionInfo)

——————————

Не удалось открыть физический файл «F:Cinema.mdf». Ошибка операционной системы 5: «5(Отказано в доступе.)». (Microsoft SQL Server, ошибка: 5120)

Чтобы получить справку, щелкните: http://go.microsoft.com/fwlink… nkId=20476

——————————
КНОПКИ:

ОК
——————————
в чем проблема?

Понравилась статья? Поделить с друзьями:
  • Sql server agent ошибка 1067
  • Sql server 2012 ошибка 1067
  • Sql error 54001 ошибка превышен предел глубины стека
  • Sql server 2012 коды ошибок
  • Sql error 42p01 ошибка отношение не существует