For some weird reason I’m having problems executing a bulk insert.
BULK INSERT customer_stg
FROM 'C:UsersMichaelworkspacepydbdataandrew.out.txt'
WITH
(
FIRSTROW=0,
FIELDTERMINATOR='t',
ROWTERMINATOR='n'
)
I’m confident after reading this that I’ve setup my user role correctly, as it states…
Members of the bulkadmin fixed server role can run the BULK INSERT statement.
I have set the Login Properties for the Windows Authentication correctly (as seen below).. to grant server-wide permissions on bulkadmin

(source: iforce.co.nz)
And the command EXEC sp_helpsrvrolemember 'bulkadmin' tells me that the information above was successful, and the current user Michael-PCMichael has bulkadmin permissions.

(source: iforce.co.nz)
But even though I’ve set everything up correctly as far as I know, I’m still getting the error. executing the bulk insert directly from SQL Server Management Studio.
Msg 4861, Level 16, State 1, Line 2
Cannot bulk load because the file «C:UsersMichaelworkspacepydbdataandrew.out.txt» could not be opened. Operating system error code 5(Access is denied.).
which doesn’t make sense because apparently bulkadmins can run the statement, am I meant to reconfigure how the bulkadmin works? (I’m so lost). Any ideas on how to fix it?
First published on MSDN on Oct 29, 2010
While there are various forms of bulk copy this blog specifically deals with copying data from a file into SQL Server. It deals about the specific error “Operating system error code 5(Access is denied.)” which might crop up under certain circumstances when doing a bulk copy. For a while now I worked with a lot of DBAs and Developers bewildered with the problem and most of them complaining about the lack of good documentation about it and hours spent diagnosing in the wrong direction. If you are looking for details about bulk copy visit
http://msdn.microsoft.com/en-us/library/ms130809(SQL.90).aspx
You run the following query
BEGIN
BULK INSERT ENVPOT_R
FROM ‘\advdev64BulkTesttest_bulk_insert.txt’
WITH ( FIELDTERMINATOR = ‘;’, ROWTERMINATOR = ‘n’)
END
And end up getting the following error
Msg 4861, Level 16, State 1, Line 1
Cannot bulk load because the file
»
\advdev64BulkTesttest_bulk_insert.txt
» could not be opened.
Operating system error code 5(Access is denied.).
The usual troubleshooting that DBAs do is to chase the “Access Denied” error from a file/folder access perspective. Some of them are as follows.
a) Added “full” access to “everyone” (just temporary to test this) on the
BulkTest
folder and still getting the same error.
b) Added “full” access to the SQL server service account on the
BulkTest
folder and still get the same error.
c) The user is made a member of the
bulkadmin
fixed server role.
Many DBAs come with prior experience on SQL Server 2000 where the following was true.
Once a user was authenticated, access to external files was based on the security profile of the SQL Server process. When the SQL Server process had read access to a file, for a user that did not have access to the file but was a member of the
bulkadmin
fixed server role, the user could import the file by using BULK INSERT and access the contents of the file.
But that had a security issue and the way SQL Server 2005 and later versions handle access to external files is different.
The following are the salient points you need to keep in consideration and are also mentioned in detail here
http://msdn.microsoft.com/en-us/library/ms175915(SQL.90).aspx
a) The data file must be shared between the two computers
b) To specify a shared data file, use its universal naming convention (UNC) name, which takes the general form of
\
Servername
Sharename
…
.
c) The user account that is used by SQL Server must have been granted the permissions that are required for reading the file on the remote disk.
But there is another important consideration that needs to be taken care of when we have a setting as below and Windows authentication is being used.
Client application from client machine à SQL Server (SQL service account impersonating client account)
\File
Server (impersonated client credentials)
a) We need to have CIFs SPN for the file server.
Whenever a computer is joined to a domain, it is assigned 2 SPN’s by default: HOST/netbiosName, and HOST/FQDN.com. netbiosName being the machine name of the computer being joined to the domain, and FQDN.com being the fully qualified machine name. These two SPN’s use the generic «HOST» service type which includes all the various services that *come*be default with Windows. Therefore, if we connect to
http://machineName
or
http://machineName.company.com
, we will already have SPN’s set that will handle Kerberos when using those names. When trying to connect to
\machineNameSomeShareName
we would be all set for Kerberos (UNC’s need a «CIFS» SPN which is included under «HOST» also).
Complete list of the different service types included in HOST of can be found in
this
technet article.
b) Configuring Kerberos delegation on the SQL Server box.
The requirements are as follows.
i) A domain user running the query from management studio must not have the Account is sensitive and cannot be delegated selected option.
ii) SPNs must be registered for the SQL Server service if the service account is a domain account.
iii) The client must be connecting to the SQL using TCP.
http://support.microsoft.com/default.aspx?scid=kb;EN-US;811889
The service’s SPN must be registered by a domain administrator if the service account is a domain user account. If the service account uses the computer’s account, then the process can register by itself or the local administrator can register it by using Setspn.
At a command prompt, type:
setspn –L Account domainsqlServiceAccount
These two SPNs for SQL service account must come up for delegation to properly function:
•One for MSSQLSvc/Host:1433, where Host is the name of the host computer.
•One for MSSQLSvc/FQDN:1433 where FQDN is the fully qualified domain name of the computer running SQL Server .
The port number at the end may vary depending on the actual port the SQL Server is listening on. For the sake of brevity I have assumed the default port 1433.
If there are no MSSQLSvc SPNs listed or there is an SPN missing, then we need to add the appropriate SPN using the setspn –A command for delegation to work properly.
At a command prompt, type:
setspn -A MSSQLSvc/< Host >:<Port> <SQL_Service_Account>
setspn -A MSSQLSvc/<FQDN>:<Port> <SQL_Service_Account>
A sample is as below
setspn -A MSSQLSvc/MySQLServer:1433 domainsqlServiceAccount
setspn -A MSSQLSvc/MySQLServer.MyDomain.com:1433 domainsqlServiceAccount
iv)The SQL Server service account must be trusted for delegation.
Once the delegation is set properly the bulk copy should work fine and we shouldn’t get any errors.
I am not delving deep into Kerberos troubleshooting as the same is well documented in another blog by my colleague here. The same can be referred if we still continue getting Kerberos related errors.
Author : Angshuman(MSFT), SQL Developer Engineer, Microsoft
Reviewed by : SMAT(MSFT), SQL Escalation Services, Microsoft
- Remove From My Forums
-
Question
-
Please help me out.
I double check permission with the account, everything looks good but still getting error message.
Thanks
Kumar
KG, MCTS
Answers
-
Msg 4861, Level 16, State 1, Procedure LKUP_BAS8REN5_TEMP, Line 18 Cannot bulk load because the file "\VAPP-CPB-SQLShardFilesFileName.txt" could not be opened. Operating system error code 5(Access is denied.). Msg 4413, Level 16, State 1, Line 3 Could not use view or function 'vTxtFileTemp' because of binding errors.
I double checked both my login as well as SQL Server Service Account has read/write access to the FILE SERVER location «\VAPP-CPB-SQLShardFiles«
This is expected behaviour
{
Security Account Delegation (Impersonation)If a SQL Server user is logged in using Windows Authentication, the user can read only the files accessible to the user account, independent of the security profile of the SQL Server process.
When executing the BULK INSERT statement by using sqlcmd or osql, from one computer, inserting data into SQL Server on a second computer,
and specifying a data_file on third computer by using a UNC path, you may receive a 4861 error.
Balmukund Lakhani | Please mark solved if I’ve answered your question, vote for it as helpful to help other user’s find a solution quicker
———————————————————————————
This posting is provided «AS IS» with no warranties, and confers no rights.
———————————————————————————
My Blog |
Team Blog | @Twitter-
Proposed as answer by
Tuesday, July 12, 2011 11:30 PM
-
Marked as answer by
Kalman Toth
Monday, October 1, 2012 12:33 AM
-
Proposed as answer by
- Remove From My Forums
-
Question
-
Please help me out.
I double check permission with the account, everything looks good but still getting error message.
Thanks
Kumar
KG, MCTS
Answers
-
Msg 4861, Level 16, State 1, Procedure LKUP_BAS8REN5_TEMP, Line 18 Cannot bulk load because the file "\VAPP-CPB-SQLShardFilesFileName.txt" could not be opened. Operating system error code 5(Access is denied.). Msg 4413, Level 16, State 1, Line 3 Could not use view or function 'vTxtFileTemp' because of binding errors.
I double checked both my login as well as SQL Server Service Account has read/write access to the FILE SERVER location «\VAPP-CPB-SQLShardFiles«
This is expected behaviour
{
Security Account Delegation (Impersonation)If a SQL Server user is logged in using Windows Authentication, the user can read only the files accessible to the user account, independent of the security profile of the SQL Server process.
When executing the BULK INSERT statement by using sqlcmd or osql, from one computer, inserting data into SQL Server on a second computer,
and specifying a data_file on third computer by using a UNC path, you may receive a 4861 error.
Balmukund Lakhani | Please mark solved if I’ve answered your question, vote for it as helpful to help other user’s find a solution quicker
———————————————————————————
This posting is provided «AS IS» with no warranties, and confers no rights.
———————————————————————————
My Blog |
Team Blog | @Twitter-
Proposed as answer by
Tuesday, July 12, 2011 11:30 PM
-
Marked as answer by
Kalman Toth
Monday, October 1, 2012 12:33 AM
-
Proposed as answer by
Проблема
При попытке подключить базу данных в Autodesk Data Management Server Console появляется следующее сообщение об ошибке:
—
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
- Нажмите клавиши Windows Start Key + R.
- Запустится апплет «Run».
- Введите Services.msc.
- Нажмите «ОК».
- Найдите службу SQL Server (AUTODESKVAULT).
- Учетная запись службы — это значение, отображаемое в поле «Вход в систему как».
- Убедитесь, что в учетной записи службы имеется полный доступ к папке данных SQL и ко всем содержащимся в ней файлам.
См. также:
- Сообщение «При выполнении команды CREATE FILE произошла ошибка операционной системы 2 (системе не удалось найти указанный файл)…» при попытке подключения базы данных к SQL Server
- Сообщение «При выполнении команды СОЗДАТЬ ФАЙЛ произошла ошибка операционной системы 32 (процесс не может получить доступ к файлу, так как он используется другим процессом)…» при подключении хранилища с помощью консоли ADMS
Программы
Vault Basic, Vault Professional, Vault Workgroup

- Remove From My Forums
-
Вопрос
Ответы
-
Hi
The error 5 is an «access denied» error.
You may need to use an admin account to actually change the security on the file such that the sql server process can open it.For your data_file.mdf diretory, make sure the user security group has write and create data permission.or
If you work with Vista, run SQL Server «as Administrator» to launch SQL Server Management Studio.
-Sreekar
-
Помечено в качестве ответа
hfinny
10 марта 2010 г. 16:08
-
Помечено в качестве ответа
Все ответы
-
Hi
The error 5 is an «access denied» error.
You may need to use an admin account to actually change the security on the file such that the sql server process can open it.For your data_file.mdf diretory, make sure the user security group has write and create data permission.or
If you work with Vista, run SQL Server «as Administrator» to launch SQL Server Management Studio.
-Sreekar
-
Помечено в качестве ответа
hfinny
10 марта 2010 г. 16:08
-
Помечено в качестве ответа
-
option 2 worked. Thank you!!! I am running Vista and running as the administrator worked.
-
Hi
The error 5 is an «access denied» error.
You may need to use an
admin account to actually change the security on the file such that the sql server process can open it.For your data_file.mdf diretory, make sure the user security group has write and create data permission.or
If you work with Vista, run SQL Server «as Administrator» to launch SQL Server Management Studio.
-Sreekar
I followed you and got the reason. Thanks a lot.
- Remove From My Forums
Присоединение базы данных
-
Вопрос
-
Вообщем, совершил глупость. Вместо отсоединения базы данных, удалил ее. Вернее, не ту удалил. Была копия базы, сделанная простым копированием. Так вот ее присоединить не удалось. Пишет «ошибка операционной системы 5:»(Отказано в доступе»). (Microsoft Sql
Server, ошибка 5120). У меня WINDOWS 7 Как выйти из ситуации?
Ответы
-
Попробуйте снять с файла все разрешения (ну или дать учетной записи, под которой запущен MS SQL разрешения на оба файла), также снимите все атрибуты, а вот потом попробуйте подключить.
Ну а если не поможет, то да, backup и restore.
-
Помечено в качестве ответа
12 июля 2012 г. 17:26
-
Помечено в качестве ответа
По какой-то странной причине у меня возникают проблемы с выполнением массовой вставки.
BULK INSERT customer_stg
FROM 'C:UsersMichaelworkspacepydbdataandrew.out.txt'
WITH
(
FIRSTROW=0,
FIELDTERMINATOR='t',
ROWTERMINATOR='n'
)
Я уверен после прочтения это что я правильно настроил свою роль пользователя, как указано…
Члены фиксированной роли сервера bulkadmin могут выполнять оператор BULK INSERT.
Я установил Login Properties для проверки подлинности Windows правильно (как показано ниже).. для предоставления разрешений на уровне сервера на bulkadmin

(источник: iforce.co.nz)
И команда EXEC sp_helpsrvrolemember 'bulkadmin' сообщает мне, что приведенная выше информация была успешной, и текущий пользователь Michael-PCMichael и bulkadmin разрешения.

(источник: iforce.co.nz)
Но даже если я все настроил правильно, насколько я знаю, я все еще получаю сообщение об ошибке. выполнение массовой вставки непосредственно из SQL Server Management Studio.
Msg 4861, уровень 16, состояние 1, строка 2
Невозможно выполнить массовую загрузку, так как не удалось открыть файл «C:UsersMichaelworkspacepydbdataandrew.out.txt». Код ошибки операционной системы 5 (отказано в доступе).
что не имеет смысла, потому что очевидно bulkadmins может запустить оператор, я должен перенастроить, как bulkadmin работает? (Я так потерян). Любые идеи о том, как это исправить?
Вопрос:
У меня есть файл базы данных .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
Не нужно делать все это. Просто щелкните правой кнопкой мыши файлы базы данных и добавьте разрешение всем. Это будет работать точно.