Ошибка sql server права доступа

5 626

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

Для того чтобы предоставить разрешения на директорию необходимо:

  1. С помощью проводника Windows перейдите в папку файловой системы, в которой находятся файлы базы данных. Правой кнопкой мыши щелкните эту папку и выберите пункт Свойства.
  2. На вкладке Безопасность щелкните Изменить и затем ― Добавить.
  3. В диалоговом окне Выбор пользователей, компьютеров, учетных записей служб или групп щелкните Расположения, в начале списка расположений выберите имя своего компьютера и нажмите кнопку ОК.
  4. В поле Введите имена объектов для выбора введите имя идентификатора безопасности службы, указанное в разделе Настройка учетных записей службы и разрешений Windows электронной документации. (В качестве идентификатора безопасности службы компонента Компонент Database Engine используйте NT SERVICEMSSQLSERVER для экземпляра по умолчанию или NT SERVICEMSSQL$InstanceName — для именованного экземпляра.)
  5. Щелкните Проверить имена, чтобы проверить введенные данные. Проверка зачастую выявляет ошибки, по ее окончании может появиться сообщение о том, что имя не найдено. При нажатии кнопки ОК открывается диалоговое окно Обнаружено несколько имен. Теперь выберите идентификатор безопасности службы MSSQLSERVER или NT SERVICEMSSQL$InstanceName и нажмите кнопку ОК. Снова нажмите кнопку ОК , чтобы вернуться в диалоговое окно Разрешения.
  6. В поле имен Группа или пользователь выберите имя идентификатора безопасности службы, а затем в поле Разрешения для <имя> установите флажок Разрешить для параметра Полный доступ.
  7. Нажмите кнопку Применить, а затем дважды кнопку ОК, чтобы выполнить выход.

Источник: https://docs.microsoft.com/ru-ru/sql/database-engine/configure-windows/configure-file-system-permissions-for-database-engine-access

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

Rob

45.2k24 gold badges122 silver badges150 bronze badges

asked Feb 24, 2010 at 23:19

JMarsch's user avatar

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

MandoMando's user avatar

MandoMandoMandoMando

5,1954 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

Noah Hawkins's user avatar

answered Mar 5, 2010 at 18:04

JMarsch's user avatar

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

goku_da_mastergoku_da_master

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

gvlasov

18.4k20 gold badges73 silver badges109 bronze badges

answered Feb 4, 2015 at 16:17

Leonardo's user avatar

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

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

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

Artjom B.

61k24 gold badges124 silver badges222 bronze badges

answered Dec 11, 2015 at 14:50

Rahul garg aggarwal's user avatar

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

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

dnguyen's user avatar

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

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

djeidot's user avatar

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

Wolf's user avatar

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

NotMe's user avatar

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

Jeroen's user avatar

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

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

toddmo's user avatar

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

Adrian O'Connor's user avatar

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

Paola's user avatar

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

praveen's user avatar

praveenpraveen

12k1 gold badge41 silver badges49 bronze badges

Copy Database to an other folder and attach or Log in SQLServer with «Windows Authentication»

enter image description here

answered May 16, 2015 at 8:23

Chưa biết's user avatar

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

sudhansu63

5,9654 gold badges39 silver badges51 bronze badges

answered Mar 2, 2010 at 13:57

Trevoke's user avatar

TrevokeTrevoke

4,1051 gold badge27 silver badges48 bronze badges

1

enter image description here

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

Valentin Petkov's user avatar

0

I was facing same issue in VS 2019. if anyone still facing same issue then please make sure you have/do following things:

  1. You should have SQL Express installed on your m/c
  2. 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
  3. Add ‘User Instance = True’ to your connectionstring
  4. 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_90's user avatar

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

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

Erik Forsmyr's user avatar

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

databaseUser's user avatar

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.

SQL Server 2005 Expess – How to fix error 3417

(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

marknuzz's user avatar

marknuzzmarknuzz

2,7871 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_'s user avatar

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

Art's user avatar

Проблемы

Рассмотрим следующую ситуацию. Чтобы усилить безопасность, удалите некоторые права пользователей по умолчанию в группу локальных администраторов операционной системе Windows. В процессе подготовки к настройке Microsoft SQL Server на этом компьютере добавьте учетную запись для установки в группу локальных администраторов.

В этом случае после установки или обновления до Microsoft SQL Server, сбой в процессе установки, и получать различные сообщения об ошибках, описанных в следующих разделах.

Сценарий 1: Для новой установки программа установки не выполняется и появляется следующее сообщение об ошибке:

Отказано в доступе

Кроме того могут появиться сообщения об ошибках, в файле Detail.txt отображать следующее:

2009-01-02 00:13:17 SQLEngine:—SqlServerServiceSCM: Ожидание событий nt «NIIT$ GlobalsqlserverRecComplete» должен быть создан

2009-01-02 13:00:20 SQLEngine:—SqlServerServiceSCM: Ожидание событий nt «NIIT GlobalsqlserverRecComplete$» или дескриптор процесса sql сигнала

2009-01-02 13:00:20 Slp: сбой действия конфигурации для функции SQL_Engine_Core_Inst во время ConfigRC и сценарий ConfigRC.

2009-01-02 13:00:20 Slp: доступ запрещен

2009-01-02 13:00:20 Slp: сбой действия конфигурации для функции SQL_Engine_Core_Inst во время ConfigRC и сценарий ConfigRC.

2009-01-02 13:00:20 Slp: System.ComponentModel.Win32Exception: Отказано в доступе

2009-01-02 13:00:20 Slp: в System.Diagnostics.ProcessManager.OpenProcess (Int32 processId, доступ Int32, Boolean throwIfExited)

2009-01-02 13:00:20 Slp: в System.Diagnostics.Process.GetProcessHandle (доступ к Int32, Boolean throwIfExited)

2009-01-02 13:00:20 Slp: в System.Diagnostics.Process.OpenProcessHandle()

2009-01-02 13:00:20 Slp: в System.Diagnostics.Process.get_Handle()

2009-01-02 13:00:20 Slp: в Microsoft.SqlServer.Configuration.SqlEngine.SqlServerServiceBase.WaitSqlServerStart (процесс processSql)

2009-01-02 13:00:20 Slp: в Microsoft.SqlServer.Configuration.SqlEngine.SqlServerServiceSCM.StartSqlServer (String [] parameters)

2009-01-02 13:00:20 Slp: в Microsoft.SqlServer.Configuration.SqlEngine.SqlServerStartup.StartSQLServerForInstall (строка sqlCollation, masterFullPath строка, логическое isConfiguringTemplateDBs)

2009-01-02 13:00:20 Slp: в Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineDBStartConfig.ConfigSQLServerSystemDatabases (EffectiveProperties свойства, логическое isConfiguringTemplateDBs, логическое useInstallInputs)

2009-01-02 13:00:20 Slp: в Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineDBStartConfig.DoCommonDBStartConfig (ConfigActionTiming время)

2009-01-02 13:00:20 Slp: в Microsoft.SqlServer.Configuration.SqlEngine.SqlEngineDBStartConfig.Install (ConfigActionTiming времени, словарь «2 actionData, PublicConfigurationBase spcb)

2009-01-02 13:00:20 Slp: в Microsoft.SqlServer.Configuration.SqlConfigBase.PrivateConfigurationBase.Execute (ConfigActionScenario сценарий, ConfigActionTiming времени, словарь «2 actionData, PublicConfigurationBase spcbCurrent)

2009-01-02 13:00:20 Slp: в Microsoft.SqlServer.Configuration.SqlConfigBase.SqlFeatureConfigBase.Execute (ConfigActionScenario сценарий, ConfigActionTiming времени, словарь «2 actionData, PublicConfigurationBase spcbCurrent)

2009-01-02 13:00:20 Slp: в Microsoft.SqlServer.Configuration.SqlConfigBase.SlpConfigAction.ExecuteAction (строка actionId)

2009-01-02 13:00:20 Slp: в Microsoft.SqlServer.Configuration.SqlConfigBase.SlpConfigAction.Execute (строка actionId, TextWriter errorStream)

2009-01-02 13:00:20 Slp: исключение: System.ComponentModel.Win32Exception.

2009-01-02 13:00:20 Slp: источник: системы.

2009-01-02 13:00:20 Slp: сообщение: доступ запрещен.

Сценарий 2: обновление до SQL Server 2008 сообщит следующее сообщение об ошибке для правила Engine_SqlEngineHealthCheck:

Имя: Engine_SqlEngineHealthCheck описание правила правило: проверяет, является ли можно перезапустить службу SQL Server; или для кластеризованного экземпляра ли SQL Server ресурс находится в оперативном режиме. Результат: Ошибка сообщение/меры по исправлению: не удается перезапустить службу SQL Server; или для кластеризованного экземпляра SQL Server ресурс находится в автономном режиме

Кроме того могут появиться сообщения об ошибках, следующим в файле Detail.txt

2009-05-27 17:50:20 SQLEngine:: механизм проверки контрольной точки «GetSqlServerProcessHandle_1» 2009-05-27 17:50:20 SQLEngine:—SqlServerServiceSCM: Ожидание событий nt «GlobalsqlserverRecComplete$ SQL10» в created2009-05-27 17:50:22 SQLEngine:— SqlServerServiceSCM: Ожидание событий nt «GlobalsqlserverRecComplete$ SQL10» или дескриптор процесса sql для signaled2009-05-27 17:50:22 SQLEngine:—FacetSqlEngineHealthCheck: Engine_SqlEngineHealthCheck: ошибка: доступ запрещен

Scenario3: Сбой установки Microsoft SQL Server 2012 или Microsoft SQL Server 2008 R2

Появится следующее сообщение об ошибке при попытке установить новый экземпляр SQL Server 2012 или SQL Server 2008 R2:

Сбой правила «Настройка учетной записи права». Счет, на котором выполняется программа установки SQL Server не имеет одно или все следующие права: право архивировать файлы и каталоги, право на управление аудитом и журнал безопасности и право на отладку программ. Чтобы продолжить, воспользуйтесь учетной записью с обоих этих прав.

Сценарий 4: Установка SQL Server 2012 или более поздней версии экземпляра завершается неудачей при указании общего сетевого ресурса (UNC-путь) для каталога резервного копирования. При возникновении этой проблемы появляется следующее сообщение об ошибке:

Учетную запись для установки SQL Server не имеет право SeSecurityPrivilege на сервере указанный файл в папке < расположение архива UNC >. Эта привилегия необходима в действие параметра безопасности папки программы установки SQL Server. Чтобы предоставить эту привилегию, добавить учетную запись для установки SQL Server в политику «Управление аудитом и журналом безопасности» с помощью консоли локальной политики безопасности на файловом сервере. Этот параметр доступен в разделе «Назначение прав пользователя» в разделе локальные политики в консоли локальной политики безопасности.

Примечание. Эта проблема возникает, так как учетная запись для установки SQL Server не имеет права SeSecurityPrivilege на файловом сервере, на котором размещается общий сетевой ресурс.

Причина

Данное поведение является особенностью. Помимо добавления учетной записи пользователя, на котором выполняется программа установки локального администратора, учетной записи пользователя программы установки требуются следующие права пользователя по умолчанию для успешного завершения установки.

Отображаемое имя объекта локальной политики

Право пользователя

Архивация файлов и каталогов

Разрешенные

Отладка программ

SeDebugPrivilege

Управление аудитом и журналом безопасности

SeSecurityPrivilege

Примечание. Дополнительные сведения о разрешениях, необходимых для установки SQL Server обратитесь к разделу «Необходимые условия» следующих статьях MSDN:

Как: установить SQL Server 2008 (программа установки)

Установка SQL Server 2012 с помощью мастера установки (программа установки)

Кроме того Если в общей папке SMB используется как параметр хранения данных каталога и другие каталоги (каталог пользователя базы данных, каталог журнала пользователя базы данных, каталог базы данных TempDB, каталог журнала базы данных TempDB или каталог резервного копирования), следующие дополнительные разрешения требуется для установки учетной записи на SMB файлового сервера, как описано в следующей статье MSDN:


Установить SQL Server с общей папке SMB в качестве варианта хранения

SMB сетевой папке

ПОЛНЫЙ ДОСТУП

Учетную запись для установки SQL

SMB сетевой папке

ПОЛНЫЙ ДОСТУП

Учетная запись службы агента SQL Server и SQL Server

Файлового сервера SMB

SeSecurityPrivilege

Учетную запись для установки SQL

Решение

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

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

  2. Нажмите кнопку Пуск, выберите пункт выполнить, введите Control admintoolsи нажмите кнопку ОК.

  3. Дважды щелкните значок Локальная политика безопасности.

  4. В диалоговом окне Локальные параметры безопасности щелкните Локальные политики, дважды щелкните Назначение прав пользователяи дважды щелкните Архивация файлов и каталогов.

  5. В диалоговом окне Архивация файлов и каталогов свойства нажмите кнопку Добавить пользователя или группу.

  6. В диалоговом окне Выбор пользователей или групп введите учетную запись пользователя, который используется для установки и два раза нажмите кнопку ОК .

  7. Повторите эту процедуру для других двух политик, упомянутых в разделе «Причина».

  8. В меню файл выберите команду Exit , чтобы закрыть диалоговое окно Локальные параметры безопасности .

Дополнительная информация

  • Чтобы проверить список привилегий, которые в настоящее время связаны с учетной записи, которая используется для установки, можно использовать средство AccessChk.exe. Чтобы загрузить данное средство, обратитесь по следующему адресу:

http://technet.microsoft.com/en-us/sysinternals/bb664922.aspx

Использование: accesschk.exe — < настройки учетной записи > *

Пример:

c:toolsaccesschk.exe — testdcsetupaccount *

Пример вывода:

SeSecurityPrivilege
Разрешенные
SeRestorePrivilege
SeSystemtimePrivilege
SeShutdownPrivilege
SeRemoteShutdownPrivilege
SeTakeOwnershipPrivilege
SeDebugPrivilege
SeSystemEnvironmentPrivilege
SeSystemProfilePrivilege
SeProfileSingleProcessPrivilege
SeIncreaseBasePriorityPrivilege
SeLoadDriverPrivilege
SeCreatePagefilePrivilege
SeIncreaseQuotaPrivilege
SeChangeNotifyPrivilege
SeUndockPrivilege
SeManageVolumePrivilege
SeImpersonatePrivilege
Право
SeTimeZonePrivilege
SeCreateSymbolicLinkPrivilege
SeInteractiveLogonRight
SeNetworkLogonRight
SeBatchLogonRight
SeRemoteInteractiveLogonRight

  • Настройка учетных записей служб Windows

  • Часто задаваемые вопросы

    • Почему при SeSecurityPrivilege на файловом сервере для каталога резервного копирования на общий ресурс UNC?

Это разрешение требуется для извлечения списков ACL в каталоге резервных копий по умолчанию убедитесь, что учетная запись службы SQL Server имеет все разрешения на папку. Это также задает списки управления доступом, если разрешения для учетной записи службы SQL, чтобы он мог выполнять резервной копии в каталоге. Программа установки выполняет эти проверяет каталог резервного копирования по умолчанию таким образом, если резервное копирование выполняется в каталоге резервных копий по умолчаниюПосле установки, пользователь не возникает ошибка или проблема ()из-за отсутствия разрешений)При выполнении резервного копирования в каталог по умолчанию.

Примечание. Нужно изменить get и set SeSecurityPrivilege ACL из папок и вложенных папок. Это так, потому что даже пользователи, имеющие разрешения на полный доступ для каталогов нет разрешений для получения или задания данных владельца и аудита из каталога.

    • Почему возникает ошибка, описанная в сценарий 4тольков SQL Server 2012 и более поздних версиях SQL Server?

В SQL Server 2012 и более поздних версий корпорация Майкрософт начала вспомогательные файлы данных и журнала в общей папке SMB. Как часть этого улучшения установки дополнительных был улучшен для усилить чеки, таким образом, клиенты не возникает ошибок или проблем из-за недостаточных разрешений после установки. В версиях SQL Server pre 2012 клиентов по-прежнему настраивается сетевой путь общего каталога резервного копирования когда учетная запись службы SQL не имеет разрешения на выполнение резервного копирования. Тем не менее они возникнут ошибки после установки в этой ситуации. Эти сценарии теперь запрещена при запуске проверки установки SQL 2012 на общем сетевом ресурсе.

Описание MS SQL Права учетной записи программы установки

Столкнулся с такой проблемой удаления экземпляра Microsoft SQL Server 2017:

Ошибка гласит:
Проверка правила «Права учетной записи программ установки» окончилась неудачно.
Учетная запись, выполняющая установку SQL Server, не имеет части следующих прав: права архивации файлов и папок, права управления аудитом и журналами безопасности и права отладки программ. Чтобы продолжить установку, войдите в систему с учетной записью, имеющей все эти права.

Решение MS SQL Права учетной записи программы установки

1) Идем в оснастку Локальная политика безопасности
Win + R и вводим secpol.msc
Другие полезные команды в шпаргалке по musthave командам Windows

2) В открывшейся оснастке идем в Параметры безопасности > Локальные политики > Назначение прав пользователя 

3) Добавляем своего пользователя в группы Восстановление файлов и каталогов, Отладка программ, Управление аудитом и журналом безопасности

4) Если у вас Active Directory и вы по бестпрактису секюрности домена убрали всех пользователей из группы Отладка программ, как я :), то идем на контроллер домена, ищем в GPO политику и временно добавляем себя в эту группу, а после установки/удаления MS SQL Server, возвращаем всё как было.

5) Всё работает, Вы восхитительны

Если Вам было полезно или есть вопросы, оставляйте комментарии, всем удачи 🙂

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

Rob

45k24 gold badges120 silver badges149 bronze badges

asked Feb 24, 2010 at 23:19

JMarsch's user avatar

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

MandoMando's user avatar

MandoMandoMandoMando

5,1154 gold badges27 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

Noah Hawkins's user avatar

answered Mar 5, 2010 at 18:04

JMarsch's user avatar

JMarschJMarsch

21.4k15 gold badges75 silver badges122 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_master's user avatar

goku_da_mastergoku_da_master

4,1471 gold badge39 silver badges41 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's user avatar

gvlasov

17.7k19 gold badges69 silver badges106 bronze badges

answered Feb 4, 2015 at 16:17

Leonardo's user avatar

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

Rolwin CrastaRolwin Crasta

4,1593 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 Kepp's user avatar

Al KeppAl Kepp

5,7632 gold badges27 silver badges47 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.'s user avatar

Artjom B.

60.7k24 gold badges124 silver badges221 bronze badges

answered Dec 11, 2015 at 14:50

Rahul garg aggarwal's user avatar

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

Nick CraverNick Craver

619k136 gold badges1293 silver badges1152 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

dnguyen's user avatar

dnguyendnguyen

1491 gold badge2 silver badges11 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.H's user avatar

Ema.HEma.H

2,8543 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

djeidot's user avatar

djeidotdjeidot

4,5144 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

Wolf's user avatar

WolfWolf

6,2322 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

NotMe's user avatar

NotMeNotMe

86.9k27 gold badges172 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

Jeroen's user avatar

JeroenJeroen

59k37 gold badges204 silver badges324 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 Mathews's user avatar

Brad MathewsBrad Mathews

1,4432 gold badges20 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

toddmo's user avatar

toddmotoddmo

19.6k13 gold badges91 silver badges102 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

Adrian O'Connor's user avatar

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

Paola's user avatar

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

praveen's user avatar

praveenpraveen

12k1 gold badge41 silver badges49 bronze badges

Copy Database to an other folder and attach or Log in SQLServer with «Windows Authentication»

enter image description here

answered May 16, 2015 at 8:23

Chưa biết's user avatar

Chưa biếtChưa biết

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

sudhAnsu63

5,8804 gold badges39 silver badges51 bronze badges

answered Mar 2, 2010 at 13:57

Trevoke's user avatar

TrevokeTrevoke

4,0951 gold badge26 silver badges48 bronze badges

1

enter image description here

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

Valentin Petkov's user avatar

0

I was facing same issue in VS 2019. if anyone still facing same issue then please make sure you have/do following things:

  1. You should have SQL Express installed on your m/c
  2. 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
  3. Add ‘User Instance = True’ to your connectionstring
  4. 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_90's user avatar

Ashu_90Ashu_90

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

Chris MoschiniChris Moschini

36.1k19 gold badges159 silver badges187 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

Erik Forsmyr's user avatar

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

databaseUser's user avatar

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.

SQL Server 2005 Expess – How to fix error 3417

(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

marknuzz's user avatar

marknuzzmarknuzz

2,7071 gold badge25 silver badges27 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_'s user avatar

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

Art's user avatar

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

Rob

45k24 gold badges120 silver badges149 bronze badges

asked Feb 24, 2010 at 23:19

JMarsch's user avatar

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

MandoMando's user avatar

MandoMandoMandoMando

5,1154 gold badges27 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

Noah Hawkins's user avatar

answered Mar 5, 2010 at 18:04

JMarsch's user avatar

JMarschJMarsch

21.4k15 gold badges75 silver badges122 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_master's user avatar

goku_da_mastergoku_da_master

4,1471 gold badge39 silver badges41 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's user avatar

gvlasov

17.7k19 gold badges69 silver badges106 bronze badges

answered Feb 4, 2015 at 16:17

Leonardo's user avatar

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

Rolwin CrastaRolwin Crasta

4,1593 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 Kepp's user avatar

Al KeppAl Kepp

5,7632 gold badges27 silver badges47 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.'s user avatar

Artjom B.

60.7k24 gold badges124 silver badges221 bronze badges

answered Dec 11, 2015 at 14:50

Rahul garg aggarwal's user avatar

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

Nick CraverNick Craver

619k136 gold badges1293 silver badges1152 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

dnguyen's user avatar

dnguyendnguyen

1491 gold badge2 silver badges11 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.H's user avatar

Ema.HEma.H

2,8543 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

djeidot's user avatar

djeidotdjeidot

4,5144 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

Wolf's user avatar

WolfWolf

6,2322 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

NotMe's user avatar

NotMeNotMe

86.9k27 gold badges172 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

Jeroen's user avatar

JeroenJeroen

59k37 gold badges204 silver badges324 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 Mathews's user avatar

Brad MathewsBrad Mathews

1,4432 gold badges20 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

toddmo's user avatar

toddmotoddmo

19.6k13 gold badges91 silver badges102 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

Adrian O'Connor's user avatar

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

Paola's user avatar

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

praveen's user avatar

praveenpraveen

12k1 gold badge41 silver badges49 bronze badges

Copy Database to an other folder and attach or Log in SQLServer with «Windows Authentication»

enter image description here

answered May 16, 2015 at 8:23

Chưa biết's user avatar

Chưa biếtChưa biết

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

sudhAnsu63

5,8804 gold badges39 silver badges51 bronze badges

answered Mar 2, 2010 at 13:57

Trevoke's user avatar

TrevokeTrevoke

4,0951 gold badge26 silver badges48 bronze badges

1

enter image description here

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

Valentin Petkov's user avatar

0

I was facing same issue in VS 2019. if anyone still facing same issue then please make sure you have/do following things:

  1. You should have SQL Express installed on your m/c
  2. 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
  3. Add ‘User Instance = True’ to your connectionstring
  4. 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_90's user avatar

Ashu_90Ashu_90

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

Chris MoschiniChris Moschini

36.1k19 gold badges159 silver badges187 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

Erik Forsmyr's user avatar

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

databaseUser's user avatar

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.

SQL Server 2005 Expess – How to fix error 3417

(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

marknuzz's user avatar

marknuzzmarknuzz

2,7071 gold badge25 silver badges27 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_'s user avatar

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

Art's user avatar

Как восстановить права администратора в MS SQL Server

Как восстановить права администратора в MS SQL Server

В этой статье описывается, как восстановить доступ к Компонент SQL Server Database Engine в качестве системного администратора, если доступ был заблокирован. Системный администратор может утратить доступ к экземпляру SQL Server по одной из следующих причин:

Системный администратор

  • по ошибке удалены все члены предопределенной роли сервера sysadmin;
  • по ошибке удалены все группы Windows, которые являлись членами предопределенной роли сервера sysadmin;
  • имена входа, являющиеся членами предопределенной роли сервера sysadmin, принадлежат лицам, которые покинули компанию или недоступны;
  • учетная запись sa отключена, или никто не знает ее пароля.

Решение

Чтобы устранить проблему доступа, рекомендуется запустить экземпляр SQL Server в однопользовательском режиме. Этот режим не позволит устанавливать другие подключений при попытке восстановить доступ. Вы можете подключиться к экземпляру SQL Server и добавить имя входа в роль сервера sysadmin.

Можно запустить экземпляр SQL Server в однопользовательском режиме с параметрами -m или -f из командной строки. Затем любой член локальной группы администраторов на компьютере может подключиться к экземпляру SQL Server в качестве члена предопределенной роли сервера sysadmin.

При запуске экземпляра в однопользовательском режиме сначала нужно остановить службу «Агент SQL Server». В противном случае агент SQL Server может установить соединение первым, заняв единственное доступное подключение к серверу и заблокировав возможность входа.

Кроме того, неизвестное клиентское приложение может воспользоваться единственным доступным подключением, прежде чем вы сможете выполнить вход. Чтобы исключить возникновение этой ситуации, используйте параметр -m, за которым следует имя приложения, что позволит ограничить подключения одним подключением из определенного приложения. Например, запуск SQL Server с помощью -mSQLCMD разрешает только одно соединение, которое должно идентифицироваться как клиентская программа sqlcmd. Для подключения через редактор запросов в Среда Management Studio используйте -m"Microsoft SQL Server Management Studio - Query".

Важно! Не используйте -m с именем приложения в качестве средства безопасности. Клиентские приложения предоставляют имя приложения в параметрах строки подключения и могут легко указать ложное имя.

В следующей таблице приведены различные способы запуска экземпляра в однопользовательском режиме в командной строке.

Пошаговые инструкции

Далее приводятся пошаговые инструкции по предоставлению системному администратору, доступ которого было по ошибке заблокирован, разрешений для входа в SQL Server.

Предварительные требования

  • SQL Server запущен в Windows 8 или более поздней версии. Небольшие изменения для предыдущих версий SQL Server или Windows приведены там, где применимо.
  • На компьютере установлена среда SQL Server Management Studio.

Следуйте этим инструкциям, выполнив вход в систему Windows в качестве члена локальной группы администраторов.

  1. В меню «Пуск» Windows правой кнопкой мыши щелкните значок диспетчера конфигурации SQL Server и выберите пункт Запуск от имени администратора, чтобы передать учетные данные администратора в диспетчер конфигурации.
  2. На левой панели диспетчера конфигурации SQL Server выберите Службы SQL Server. На панели справа найдите свой экземпляр SQL Server. (Экземпляр по умолчанию SQL Server включает (MSSQLSERVER) после имени компьютера. Именованные экземпляры появляются в верхнем регистре с тем же названием, что и в списке «зарегистрированные серверы»). Щелкните правой кнопкой мыши экземпляр SQL Server, а затем выберите пункт Свойства.
  3. На вкладке Параметры запуска в поле Укажите параметр запуска введите параметр -m и нажмите кнопку Добавить. (Это дефис, затем буква «m» в нижнем регистре.)

Примечание. В некоторых предыдущих версиях SQL Server нет вкладки Параметры запуска . В этом случае на вкладке Дополнительно дважды щелкните Параметры запуска. Параметры открываются в очень маленьком окне. Не изменяйте существующие параметры. В самом конце добавьте новый параметр ;-m и нажмите кнопку ОК. (Это точка с запятой, затем дефис, затем буква «m» в нижнем регистре.)

4. Нажмите кнопку ОК, а после сообщения о перезагрузке щелкните правой кнопкой мыши имя сервера и выберите пункт Перезапустить.

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

6. В меню «Пуск» Windows щелкните правой кнопкой мыши значок Среда Management Studio и выберите пункт Запуск от имени администратора. Учетные данные администратора будут переданы в SSMS.

 Примечание. В более ранних версиях Windows параметр Запуск от имени администратора появляется в виде подменю.

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

a. Подключитесь с помощью обозревателя объектов, используя проверку подлинности Windows (которая включает учетные данные администратора). Разверните Безопасность, затем Имена входа и дважды щелкните имя входа. На странице Роли сервера выберите sysadmin и нажмите ОК.

b. Вместо соединения с помощью обозревателя объектов подключитесь с помощью окна запросов, используя проверку подлинности Windows (которая включает учетные данные администратора). (Подключиться подобным образом можно только в том случае, если подключение не выполнено с помощью обозревателя объектов.) Выполните следующий код, чтобы добавить новое имя входа для проверки подлинности Windows, которое является членом предопределенной роли сервера sysadmin . В следующем примере создается пользователь с именем CONTOSOPatK.

CREATE LOGIN [CONTOSOPatK] FROM WINDOWS;  
ALTER SERVER ROLE sysadmin ADD MEMBER [CONTOSOPatK];

c. Если экземпляр SQL Server работает в режиме смешанной проверки подлинности, подключитесь к окну запросов при помощи проверки подлинности Windows (которая включает учетные данные администратора). Выполните следующий код, чтобы создать новое имя входа для проверки подлинности в SQL Server, которое является членом предопределенной роли сервера sysadmin.

CREATE LOGIN TempLogin WITH PASSWORD = '************';  
ALTER SERVER ROLE sysadmin ADD MEMBER TempLogin;

Предупреждение. Замените ************ надежным паролем.

d. Если экземпляр SQL Server работает в режиме смешанной проверки подлинности и требуется изменить пароль для учетной записи sa , подключитесь к окну запросов с использованием проверки подлинности Windows (которая включает учетные данные администратора). Измените пароль учетной записи sa с помощью следующей команды.

ALTER LOGIN sa WITH PASSWORD = '************';

Предупреждение. Замените ************ надежным паролем.

7. Закройте среду Среда Management Studio.

8. Следующие действия позволят переключить SQL Server в многопользовательский режим. На левой панели диспетчера конфигурации SQL Server выберите Службы SQL Server.

9. На правой панели щелкните экземпляр SQL Serverправой кнопкой мыши и выберите пункт Свойства.

10. На вкладке Параметры запуска в поле Существующие параметры выберите -m и нажмите кнопку Удалить.

Примечание. В некоторых предыдущих версиях SQL Server нет вкладки Параметры запуска . В этом случае на вкладке Дополнительно дважды щелкните Параметры запуска. Параметры открываются в очень маленьком окне. Удалите ;-m , добавленный ранее, и нажмите ОК.

11. Щелкните правой кнопкой мыши имя сервера и выберите пункт Перезапустить. Не забудьте запустить агент SQL Server еще раз, если он был остановлен перед запуском SQL Server в однопользовательском режиме.

Теперь можно подключиться к одной из учетных записей, которая является членом предопределенной роли сервера sysadmin .

  • Remove From My Forums
  • Вопрос

  • При установке SQL server 2012 на Windows server 2012 standart на этапе конфигурации сервера «укажите учетные записи служб и параметры сортировки» я ввожу для Агента SQL Server и Ядра SQL СУБД Server одну и ту же учетку, которую специально
    перед этим завел в AD на  DC (как пользователя домена). Формат соответственно DOMANENAMEUsername. Пароль не пустой, а тот, что был при создании учетки в AD. При нажатии «Далее» выскакивает ошибка «Эта страница содержит
    ошибки ошибки проверки. Нажмите кнопку «Ок», чтобы закрыть это диалоговое окно. Посмотрите ошибки в нижней части страницы». Внизу 2 ошибки. Первая: «Отказано в доступе». Вторая : «Недопустимое имя входа
    или пароль для учетной записи службы SQL Server. Чтобы обновить учетную запись службы используйте диспетчер конфигурации SQl Server».

    На всякий случай добавил в AD username’а в группу «Администраторы», а так же добавил его в администраторы непосредственно на сервере, на котором ставится SQL Server. Уже не знаю что ему еще может не нравиться.

    P.S. До этого устанавливал SQL Server с учетными записями, прописанными по умолчанию (локальными какими то NT ServiceSQLAgent$SHAREPOINT и NT ServiceMSSQL$SHAREPOINT) и вся установка проходила нормально.

    P.P.S Надо уточнить, что оба сервера (DC и будущий SQL) находятся на разных виртуальных машинах.

    • Изменено

      15 ноября 2013 г. 6:49
      опечатка

Ответы

  • Сам решил проблему. На всякий случай, вдруг кому пригодится, распишу суть и решение:

    Заново создал в AD пользователя A, которого добавил в группу Администраторы. Под ним зашел на сервер, где планируется установка SQL Server’a. Даем нашему пользователю А права локального администратора на компьютере. После чего уже проводим установку SQL
    Server’a. Теперь этап с введение какого то пользователя в учетные записи служб (необязательного этого А) проходит нормально.

    Парадоксально, что до этого все делалось так же, только пользователь, с которого производился вход в систему, в AD числился просто пользователем домена. И на реальном железе, которое у нас стоит, этих прав вполне достаточно было для установки SQL server’a.

    • Помечено в качестве ответа
      Evgeny Zinger
      15 ноября 2013 г. 9:06

Вы можете столкнуться с ошибкой SQL Server 18456, если сервер не может аутентифицировать соединение, и это может быть вызвано недоступностью прав администратора для SQL-сервера или если протокол TCP / IP отключен в настройках SQL-сервера.

Проблема возникает, когда пользователь пытается подключиться к серверу SQL (локальному или удаленному), но обнаруживает ошибку 18456 (с разными состояниями).

Ошибка Microsoft SQL Server 18456

Вы можете исправить ошибку SQL-сервера 18456, попробовав приведенные ниже решения, но перед этим проверьте, решает ли проблему перезагрузка сервера, клиентского компьютера и сетевых компьютеров. Кроме того, убедитесь, что вы вводите правильное имя пользователя и пароль (а не копируете адрес).

Также проверьте, правильно ли вы вводите имя базы данных (без опечаток), и убедитесь, что вы соответствующим образом обновили файл конфигурации. Кроме того, проверьте, решает ли проблему разблокировка учетной записи (с помощью запроса ALTER LOGIN WITH PASSWORD = UNLOCK). Если вы видите ошибки в журнале ошибок SQL, убедитесь, что ваш SQL-сервер не атакован. И последнее, но не менее важное: убедитесь, что часы сервера и клиентского компьютера установлены правильно.

Вы можете столкнуться с ошибкой 18456, если SQL-сервер не имеет повышенных разрешений на выполнение своей операции, и запуск его от имени администратора (или отключение элементов управления UAC на сервере) может решить проблему.

Откройте SQL Server от имени администратора

  1. Щелкните Windows и введите SQL Server Management Studio.
  2. Теперь щелкните правой кнопкой мыши SMSS и выберите «Запуск от имени администратора».Запустите Microsoft SQL Server Management Studio от имени администратора.
  3. Затем нажмите Да (если получено приглашение UAC) и проверьте, не содержит ли SQL-сервер ошибки 18456.
  4. Если нет, проверьте, решает ли проблему отключение UAC на сервере.

Запуск SQL Server в однопользовательском режиме

  1. Щелкните Windows, введите и откройте диспетчер конфигурации SQL Server.
  2. Теперь щелкните правой кнопкой мыши службу SQL Server (на вкладке «Службы SQL Server») и выберите «Свойства».Откройте свойства SQL Server
  3. Затем перейдите на вкладку Параметры запуска и в поле Укажите параметр запуска введите: -m
  4. Теперь нажмите «Добавить» и примените изменения.Добавьте параметр «-m» к параметрам запуска SQL Server.
  5. Затем щелкните правой кнопкой мыши службу SQL Server и выберите «Перезагрузить».Перезапустите службу SQL Server.
  6. Теперь щелкните Windows, введите: SQL Server Management Studio, щелкните правой кнопкой мыши SMSS и выберите Запуск от имени администратора.
  7. Теперь проверьте, можете ли вы подключиться к SQL Server от имени администратора.
  8. Если это так, добавьте учетную запись домена на SQL-сервер и назначьте ей роль SysAdmin.
  9. Теперь вернитесь в окно диспетчера конфигурации SQL Server и удалите параметр -m на вкладке Параметры запуска.
  10. Затем перезапустите службу SQL Server (шаг 3) и проверьте, нормально ли работает SQL-сервер.

Если проблема не исчезнет, ​​проверьте, правильно ли настроены параметры запуска или сведения о пути. Если проблема все еще существует, убедитесь, что ваша учетная запись пользователя имеет необходимые разрешения для служб базы данных / отчетов, а затем проверьте, решена ли проблема.

Включите протокол TCP / IP в диспетчере конфигурации сервера.

Код ошибки 18456 на сервере SQL означает, что серверу не удалось аутентифицировать соединение, и это может произойти, если протокол TCP / IP, необходимый для доступа к базе данных в сети, отключен в диспетчере конфигурации сервера. В этом контексте включение TCP / IP в диспетчере конфигурации SQL Server может решить проблему.

  1. Щелкните Windows и разверните Microsoft SQL Server, указав год, например, 2008 (вам может потребоваться немного прокрутить, чтобы найти параметр).
  2. Теперь откройте диспетчер конфигурации SQL Server и нажмите Да (если получено приглашение UAC).
  3. Затем разверните сетевую конфигурацию SQL Server и выберите Протоколы для (имя сервера / базы данных) на левой панели.
  4. Теперь на правой панели дважды щелкните TCP / IP и выберите Да в раскрывающемся списке Включено.Откройте TCP / IP в протоколах конфигурации сети SQL Server
  5. Затем примените изменения и щелкните Windows.Включить TCP / IP в SQL
  6. Теперь введите «Службы», щелкните правой кнопкой мыши результат «Службы» и выберите «Запуск от имени администратора».Откройте службы в качестве администратора
  7. Затем щелкните правой кнопкой мыши SQL Server (с именем сервера) и выберите «Перезагрузить».Перезапустите службу SQL в окне служб.
  8. Теперь проверьте, очищен ли SQL-сервер от ошибки 18456.

Если это не помогло, убедитесь, что вы подключаетесь к правильному порту SQL-сервера (особенно, если вы используете сервер в многосерверной среде).

Сервер SQL может отображать ошибку 18456, если метод аутентификации сервера SQL не настроен должным образом (например: вы пытаетесь войти в систему с использованием аутентификации сервера SQL, тогда как сервер настроен на использование аутентификации Windows). В этом случае изменение метода аутентификации SQL-сервера может решить проблему. Прежде чем двигаться дальше, убедитесь, что для текущего пользователя включен статус входа в систему (например, SA).

  1. В обозревателе объектов Microsoft SQL Server Management Studio щелкните правой кнопкой мыши свой сервер и выберите «Свойства».
  2. Теперь на левой панели выберите Безопасность, а на правой панели выберите SQL Server и проверку подлинности Windows (или наоборот).Включить SQL Server и проверку подлинности Windows
  3. Затем примените изменения и в обозревателе объектов щелкните правой кнопкой мыши сервер.
  4. Теперь выберите «Перезагрузить» и после перезапуска проверьте, можете ли вы подключиться к базе данных без ошибки 18456.

Если вы не можете войти в SQL, вы можете установить MS Power Tools и выполнить следующую команду с повышенными привилегиями:

psexec.exe -i -s ssms.exe

После этого вы можете использовать учетную запись установки SQL, чтобы внести изменения, а также убедиться, что учетная запись SA не отключена:

Включите учетную запись SA и сбросьте пароль учетной записи

Если вы не можете подключиться к SQL Server, то включение учетной записи SA SQL-сервера и сброс его пароля может решить проблему.

  1. Запустите Microsoft SQL Server Management Studio (возможно, вам придется использовать учетную запись администратора домена) и разверните Безопасность.
  2. Затем дважды щелкните Logins и откройте SA.Откройте учетную запись SA в Microsoft SQL Server Management Studio.
  3. Теперь введите новый пароль и подтвердите его (убедитесь, что вы используете надежный пароль).
  4. Затем перейдите на вкладку Server Roles и убедитесь, что выбраны следующие роли: Public SysadminВключение ролей общедоступного сервера и сервера системного администратора для учетной записи SA
  5. Теперь перейдите на вкладку «Статус» и на правой панели выберите «Включено» (в разделе «Вход»).Включение учетной записи SA в SQL
  6. Затем примените изменения и нажмите кнопку Windows.
  7. Теперь введите Services и щелкните его правой кнопкой мыши.
  8. Затем выберите «Запуск от имени администратора» и перейдите к службе SQL Server.
  9. Теперь щелкните его правой кнопкой мыши и выберите «Перезагрузить».
  10. После перезапуска службы проверьте, устранена ли ошибка 18456 SQL-сервера.

Создайте новый логин и перезапустите службы Reporting Services

Если вы не можете использовать какую-либо учетную запись для подключения к базе данных, то создание новой учетной записи и перезапуск служб отчетов может решить проблему.

  1. Запустите Microsoft SQL Server Management Studio и разверните вкладку «Безопасность».
  2. Затем разверните Логины и щелкните его правой кнопкой мыши.
  3. Теперь выберите «Новый вход» и введите учетные данные (в имени входа выберите учетную запись компьютера), если используется проверка подлинности SQL Server.Создать новый логин в SQL Server
  4. Затем не забудьте снять флажок «Пользователь должен сменить пароль при следующем входе в систему» ​​и выберите базу данных.
  5. Теперь перейдите на вкладку Server Roles и выберите роль Public.
  6. Затем на вкладке «Сопоставление пользователей» обязательно выберите базу данных и выберите db_owner.Выберите db_owner для базы данных в SQL
  7. Теперь примените ваши изменения и щелкните Windows.
  8. Затем введите Services и щелкните правой кнопкой мыши результат Services. Затем выберите Запуск от имени администратора.
  9. Теперь щелкните правой кнопкой мыши службу отчетов SQL Server и выберите «Перезагрузить».Перезапустите службу отчетов SQL Server.
  10. Затем повторно подключитесь к базе данных и проверьте, очищен ли сервер SQL от ошибки 18456.

Если это так, убедитесь, что вы создали пользователя в BUILTIN administrators, и затем вы можете использовать этого пользователя для управления SQL Server. Если вы восстановили базу данных из резервной копии, будет лучше удалить и повторно добавить пользователей, чтобы удалить все старые записи пользователей. Если вы хотите запустить SQL-сервер от имени другого пользователя, введите Microsoft SQL Server в поиске Windows, Shift + щелкните правой кнопкой мыши на SQL Server и выберите «Запуск от имени другого пользователя». И последнее, но не менее важное: проверьте, решает ли проблема использование Azure Data Studio с сервером SQL.

Please, pay attantion that now you are in public part of FAQ-Area. Register and find more FAQ-articles
in Personal Cabinet.

>

Technical Support FAQ

>

База знаний (FAQ)

>

Программное обеспечение

>

КОМПЛЕКС

>

ЛОЦМАН

>

Базы данных ЛОЦМАН

FAQ#700385: Ошибка создания БД. Отказано в доступе.

Keywords:

ошибка
БД
доступ
Created: 2008-07-17 11:01:38

Linked Articles:

Changed: 2010-02-24 09:31:32

Problem:

В процессе создания базы данных ЛОЦМАН появляется сообщение «Отказано в доступе» База данных не создается.

Solution:

Как правило, Microsoft SQL Server (служба SQL Server) запускается от специально выделенной для этих целей учетной записи. Ошибка, которая возникает при создании БД говорит о том, что у этой учетной записи нет соответствующих прав доступа на папку, в которой хранятся эталоны баз данных ЛОЦМАН, либо на папку, которая была указана на шаге выбора пути расположения базы данных.

Для решения проблемы необходимо предоставить учетной записи, от имени которой запускается SQL Server права на перечисленные папки.
Путь к папке с эталонами БД указан в глобальном конфигурационном файле LoodsmanCommon.ini, секция [ServerOptions], параметр EtalonPath

  • Remove From My Forums
  • Вопрос

  • Прооблема с запуском службы SQL Server 2008. Служба не запускается и в журнале ошибок выдается сообщение:
    Источник: MSSQLSERVER
    Категория: Сервер
    ID: 17058

    initerrlog: не удалось открыть файл журнала ошибок «». Ошибка операционной системы = 3(Системе не удается найти указанный путь.).

    Может кто-нибудь помочь в решении проблемы?

    Михаил

Ответы

  • Похоже, наилучее решение в этой ситуации, оставить сервер работать под системной учетной записью. Может я не прав?

    Михаил

    не совсем…

    стартовать сервер под системной записью совсем нехорошо… и небезопасно.

    созданную отдельную учетку надо  добавить в группы
    SQLServer2005MSFTEUser$ИМЯ_СЕРВЕРА$MSSQLSERVER
    SQLServer2005MSSQLUser$ИМЯ_СЕРВЕРА$MSSQLSERVER


    blog.wadmin.ru

    • Помечено в качестве ответа

      17 ноября 2009 г. 9:18

Понравилась статья? Поделить с друзьями:
  • Ошибка sql server не существует или доступ запрещен
  • Ошибка sql server interfaces error 26
  • Ошибка spn 2003 fmi 31
  • Ошибка sql primary filegroup is full
  • Ошибка spn 1675 fmi 5 шакман