Меню

Ошибка create database permission denied in database master

  1. Download the script from this Microsoft Site
  2. Run it as Administrator
  3. Follow the instructions and your set.

UPDATE 9/3/2014

The Microsoft URL above is no longer valid, someone thou took the time to save it to GitHubGist and the link is as follows https://gist.github.com/wadewegner/1677788

UPDATE 11/1/2021

Below is the entire script, don’t recall being able to do this back in 2014, I guess this one of the perks of 2021.

    @echo off
    rem
    rem ****************************************************************************
    rem
    rem    Copyright (c) Microsoft Corporation. All rights reserved.
    rem    This code is licensed under the Microsoft Public License.
    rem    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
    rem    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
    rem    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
    rem    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
    rem
    rem ****************************************************************************
    rem
    rem CMD script to add a user to the SQL Server sysadmin role
    rem
    rem Input:  %1 specifies the instance name to be modified. Defaults to SQLEXPRESS.
    rem         %2 specifies the principal identity to be added (in the form "<domain><user>").
    rem            If omitted, the script will request elevation and add the current user (pre-elevation) to the sysadmin role.
    rem            If provided explicitly, the script is assumed to be running elevated already.
    rem
    rem Method: 1) restart the SQL service with the '-m' option, which allows a single connection from a box admin
    rem            (the box admin is temporarily added to the sysadmin role with this start option)
    rem         2) connect to the SQL instance and add the user to the sysadmin role
    rem         3) restart the SQL service for normal connections
    rem
    rem Output: Messages indicating success/failure.
    rem         Note that if elevation is done by this script, a new command process window is created: the output of this
    rem         window is not directly accessible to the caller.
    rem
    rem
    setlocal
    set sqlresult=N/A
    if .%1 == . (set sqlinstance=SQLEXPRESS) else (set sqlinstance=%1)
    if /I %sqlinstance% == MSSQLSERVER (set sqlservice=MSSQLSERVER) else (set sqlservice=MSSQL$%sqlinstance%)
    if .%2 == . (set sqllogin="%USERDOMAIN%%USERNAME%") else (set sqllogin=%2)
    rem remove enclosing quotes
    for %%i in (%sqllogin%) do set sqllogin=%%~i
    @echo Adding '%sqllogin%' to the 'sysadmin' role on SQL Server instance '%sqlinstance%'.
    @echo Verify the '%sqlservice%' service exists ...
    set srvstate=0
    for /F "usebackq tokens=1,3" %%i in (`sc query %sqlservice%`) do if .%%i == .STATE set srvstate=%%j
    if .%srvstate% == .0 goto existerror
    rem
    rem elevate if <domain/user> was defaulted
    rem
    if NOT .%2 == . goto continue
    echo new ActiveXObject("Shell.Application").ShellExecute("cmd.exe", "/D /Q /C pushd ""+WScript.Arguments(0)+"" & ""+WScript.Arguments(1)+"" %sqlinstance% ""+WScript.Arguments(2)+""", "", "runas"); >"%TEMP%addsysadmin{7FC2CAE2-2E9E-47a0-ADE5-C43582022EA8}.js"
    call "%TEMP%addsysadmin{7FC2CAE2-2E9E-47a0-ADE5-C43582022EA8}.js" "%cd%" %0 "%sqllogin%"
    del "%TEMP%addsysadmin{7FC2CAE2-2E9E-47a0-ADE5-C43582022EA8}.js"
    goto :EOF
    :continue
    rem
    rem determine if the SQL service is running
    rem
    set srvstarted=0
    set srvstate=0
    for /F "usebackq tokens=1,3" %%i in (`sc query %sqlservice%`) do if .%%i == .STATE set srvstate=%%j
    if .%srvstate% == .0 goto queryerror
    rem
    rem if required, stop the SQL service
    rem
    if .%srvstate% == .1 goto startm
    set srvstarted=1
    @echo Stop the '%sqlservice%' service ...
    net stop %sqlservice%
    if errorlevel 1 goto stoperror
    :startm
    rem
    rem start the SQL service with the '-m' option (single admin connection) and wait until its STATE is '4' (STARTED)
    rem also use trace flags as follows:
    rem     3659 - log all errors to errorlog
    rem     4010 - enable shared memory only (lpc:)
    rem     4022 - do not start autoprocs
    rem
    @echo Start the '%sqlservice%' service in maintenance mode ...
    sc start %sqlservice% -m -T3659 -T4010 -T4022 >nul
    if errorlevel 1 goto startmerror
    :checkstate1
    set srvstate=0
    for /F "usebackq tokens=1,3" %%i in (`sc query %sqlservice%`) do if .%%i == .STATE set srvstate=%%j
    if .%srvstate% == .0 goto queryerror
    if .%srvstate% == .1 goto startmerror
    if NOT .%srvstate% == .4 goto checkstate1
    rem
    rem add the specified user to the sysadmin role
    rem access tempdb to avoid a misleading shutdown error
    rem
    @echo Add '%sqllogin%' to the 'sysadmin' role ...
    for /F "usebackq tokens=1,3" %%i in (`sqlcmd -S np:\.pipeSQLLocal%sqlinstance% -E -Q "create table #foo (bar int); declare @rc int; execute @rc = sp_addsrvrolemember '$(sqllogin)', 'sysadmin'; print 'RETURN_CODE : '+CAST(@rc as char)"`) do if .%%i == .RETURN_CODE set sqlresult=%%j
    rem
    rem stop the SQL service
    rem
    @echo Stop the '%sqlservice%' service ...
    net stop %sqlservice%
    if errorlevel 1 goto stoperror
    if .%srvstarted% == .0 goto exit
    rem
    rem start the SQL service for normal connections
    rem
    net start %sqlservice%
    if errorlevel 1 goto starterror
    goto exit
    rem
    rem handle unexpected errors
    rem
    :existerror
    sc query %sqlservice%
    @echo '%sqlservice%' service is invalid
    goto exit
    :queryerror
    @echo 'sc query %sqlservice%' failed
    goto exit
    :stoperror
    @echo 'net stop %sqlservice%' failed
    goto exit
    :startmerror
    @echo 'sc start %sqlservice% -m' failed
    goto exit
    :starterror
    @echo 'net start %sqlservice%' failed
    goto exit
    :exit
    if .%sqlresult% == .0 (@echo '%sqllogin%' was successfully added to the 'sysadmin' role.) else (@echo '%sqllogin%' was NOT added to the 'sysadmin' role: SQL return code is %sqlresult%.)
    endlocal

  • Remove From My Forums
  • Question

  • Hello Everyone,

    I just bought a new computer, installed Windows 10 pro, sql server 2014 Express + SSMS 2016 Preview.

    I have done this many times before and it always worked.

    1. I start SSMS «As Administrator» with Windows Authentication Mode.
    2. Then I try to create a new Database and I get an exception message.

    CREATE DATABASE permission denied in database ‘master’. (Microsoft SQL Server, Error: 262)

    SSMS 2014 Express did not work either.

    I would any appreciate any help greatly! Kindest Blessings


    Andreas Bolliger

Answers

  • Dear Andreas,

    restart the sql server service in single user mode.

    You have to add -m as a startup parameter in configuration manager and restart the service:

    From this point you will be able to connect with any local windows administrator via sqlcmd as a sysadmin (only possible in single user mode for fixing those issues)

    sqlcmd -S .<YourInstance>

    Now create your missing login

    CREATE LOGIN [<YourLogin>] FROM WINDOWS;

    GO

    Do not forget to add the created login to the sysadmin server role:

    exec sp_addsrvrolemember [<YourLogin>], sysadmin;
    GO

    Remove the -m startup parameter in SQL Server configuration manager, restart your instance and you will be able to be the real sysadmin.

    PS: the correct way is realy to add an administrative login during setup. But afterwards this way will fix your problem without re-installing your sql server.

    Best Regards

    Kai

    • Proposed as answer by

      Wednesday, May 11, 2016 8:33 PM

    • Edited by
      Koppelmann, Kai
      Wednesday, May 11, 2016 8:34 PM
      Formatting
    • Marked as answer by
      BolligeA
      Wednesday, May 11, 2016 8:40 PM

I am making a database in sql server and it shows an error that "CREATE DATABASE permission denied in database 'master'"
I am using the administrator log in itself.
What i need to do?
Please suggest a fix!

This is the screenshot and the error message i used to get when i create a database in sql server 2008

asked Aug 31, 2014 at 7:09

1

The user must be a member of dbcreator server role for user to have enough permissions to create a database.

You can execute the following statement to make a user member of dbcreator server role.

EXEC master..sp_addsrvrolemember @loginame = N'Shubhankar', @rolename = N'dbcreator'
GO

Or you Can/Should use

ALTER SERVER ROLE  [dbcreator]  ADD MEMBER [Shubhankar];
GO

Members of sysadmin role are by default members of dbcreator server role therefore they can create databases too.

answered Aug 31, 2014 at 12:49

M.Ali's user avatar

M.AliM.Ali

1,8808 gold badges26 silver badges37 bronze badges

0

All the above points are clear but there is one which is missing. I struggled to find the solution to this problem and finally got it after long research.

To get permission to create database in your local account follow the below given steps.

Step 1: Disconnect from your local account.

Step 2: Again Connect to Server with Login : sa and Password : pwd(pwd given to your local login).

Step 3: Object Explorer -> Security -> Logins -> Right click on your server name -> Properties -> Server Roles -> sysadmin -> OK

Step 4: Disconnect and connect to your local login and create database.

Successfully created the database 😀 😉

answered Aug 10, 2016 at 3:28

user103167's user avatar

user103167user103167

511 silver badge1 bronze badge

If you’re in Azure, the command is a little different:

ALTER ROLE [dbmanager] ADD MEMBER [Shubhankar];

answered Jun 16, 2021 at 17:26

Jesse Sierks's user avatar

I was having same problem, I noticed I was connected using Windows Authentication. I then disconnected and used SQL Server Authentication. It started good.

answered Feb 1, 2017 at 19:41

Baqer Naqvi's user avatar

[Решено] При создании БД выскочила ошибка — Разрешение CREATE DATABASE запрещено в базе данных «master». Что делать?  

Никак не могу создать базу данных, все делаю по инструкции но все равно выскакивает эта ошибка — Разрешение CREATE DATABASE запрещено в базе данных «master». Как это поправить?

Эта ошибка показана на рисунке выше. Она возникает по причине того что пользователю в MS SQL Server не даны права на создание баз данных. Чтобы дать права нужно запустить программу ДНД ЭТЛ Профессионал .Нет от имени администратора. Для этого сделайте следующее:

1. Перейдите в папку с установленной программой. По умолчанию это каталог:
C:Program FilesДНД Софт (ИП Рыженков)ДНД ЭТЛ Профессионал .Нет
2. Выберите файл DNDEtlPro.exe, нажмите по нему правой кнопкой мыши и в контекстном меню выберите пункт Запустить от имени Администратора.
После этого у программы ДНД ЭТЛ Профессионал .Нет будут права «Администратора», которые позволят создать Базу Данных на сервере БД без каких либо ограничений.
3. Попробуйте заново создать БД.

Все вышеперечисленные действия нужно делать только один раз, исключительно для создания Базы Данных.

Если способ выше не помог, то возможно у Вашего пользователя Windows вообще нет прав на работу в MS SQL Server. Чтобы дать ему эти права нужно сделать следующее:

1. Зайти в систему от имени пользователя с правами локального администратора
2. Запустить командную строку (CMD.exe) с правами администратора (начиная с Windows Vista по умолчанию включен UAC, поэтому для полных прав в системе все программы нужно запускать правым кликом vsib > запустить от имени от администратора)
3. Выполнить остановку службы SQL Server
net stop MSSQLSERVER

Примечание: MSSQLSERVER — Это имя экземпляра SQL Server у вас может быть другое имя, смотрите имя в Диспетчере задач на вкладке «Службы», кстати там тоже службу можно остановить.
4. Выполнить запуск службы SQL Server в однопользовательском режиме
net start MSSQLSERVER /m
5. Подключиться к командному процессору управления SQL Server с правами текущего пользователя
sqlcmd -E
6. Добавить объект безопасности Windows (локального или доменного пользователя или группу) в базу данных пользователей SQL Server
CREATE LOGIN [builtinадминистраторы] FROM WINDOWS;
GO;
7. Назначить этому пользователю права администратора SQL Server’a
EXEC sp_addsrvrolemember ‘builtinадминистраторы’, ‘sysadmin’;
GO;
8. Выйти из sqlcmd
exit
9. Запустить службу SQL Server в обычном режиме
net start MSSQLSERVER
10. Теперь можно подключаться через программу к вашему SQL серверу и выполнять необходимые действия

This post was modified 4 года назад 2 times by Денис

Денис

Денис 

(@denov)

Admin

| 117 Сообщения
0 89 1

Hi,

I’m using Visual Studio 2005 Pro and SQLExpress that comes with it.

I have my program running fine in XP Pro OS using a window user «Glen» (Computer administrator) with Administrator rights.  This means that I installed VS 2005 using this window user «Glen»

I created another windows user «TestUser» (Limited account) in the same physical PC.

I tried to run the program and on the part that I need to access SQL table, I got the error [CREATE DATABASE permission denied in database ‘master’]

At the same time while using «TestUser» and running sqlcmd (to check if I can connect to SQL), I also got error HResult 0x2, Level 16, State 1.

I read alot on MSDN discussions and related links but it seems that I can’t get the solution that I need.

SO HERE ARE MY QUESTIONS :

1.  Am I allowed to run my program using user «TestUser» since SQL is installed using «Glen» windows user?

2.  Do I need to add access rights to «TestUser» to allow the user to have CREATE rights? (Note : for security reason, I can add other access rights except Administrator)

Thanks in advance for all you help.

Hi,

I’m using Visual Studio 2005 Pro and SQLExpress that comes with it.

I have my program running fine in XP Pro OS using a window user «Glen» (Computer administrator) with Administrator rights.  This means that I installed VS 2005 using this window user «Glen»

I created another windows user «TestUser» (Limited account) in the same physical PC.

I tried to run the program and on the part that I need to access SQL table, I got the error [CREATE DATABASE permission denied in database ‘master’]

At the same time while using «TestUser» and running sqlcmd (to check if I can connect to SQL), I also got error HResult 0x2, Level 16, State 1.

I read alot on MSDN discussions and related links but it seems that I can’t get the solution that I need.

SO HERE ARE MY QUESTIONS :

1.  Am I allowed to run my program using user «TestUser» since SQL is installed using «Glen» windows user?

2.  Do I need to add access rights to «TestUser» to allow the user to have CREATE rights? (Note : for security reason, I can add other access rights except Administrator)

Thanks in advance for all you help.

Вопрос:

Я установил SQL SERVER 2008 R2 в свою систему с установленной операционной системой Windows XP.

Всякий раз, когда я пытаюсь создать новую базу данных, появляется сообщение об ошибке:

CREATE DATABASE PERMISSION DENIED IN DATABASE 'master'.(Microsoft SQL Server, Error:262)

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

у пользователя не было разрешения, но теперь я исправил это.

Ответ №1

При запуске студии управления SQL-сервером используйте пользователя “sa”, а не “Windows-User”. Похоже, что у пользователя Windows-пользователя нет разрешения.

Ответ №2

Ответ №3

Щелкните правой кнопкой мыши и запустите “SQL Server Management Studio” в качестве администратора.

Ответ №4

Причиной этой ошибки является недостаточное разрешение. Дайте пользователю роль “dbcreater” проверить роль dbcreater

Ответ №5

Если вы находитесь в ситуации, когда у вас есть доступ только к базе данных SQL/view, вы должны учитывать следующее:

  • Есть ли у вас альтернативный логин или учетные данные пользователя sa? Если это так, попробуйте это первым и, если необходимо, предоставите свои другие права на вход в систему с помощью раздела Security/Logins/.. вашей базы данных на панели Object Explorer (см. Ответ Ахмета Арслана).

  • Если у вас есть доступ к учетной записи другого пользователя Windows, у которого есть доступ через проверку подлинности Windows, попробуйте запустить ssms.exe в качестве другого пользователя с помощью команды “runas”. Полная информация и объяснение здесь в ответе от SqlRyan.

  • Если у вас есть старые базы данных из предыдущей установки Windows, настроенной с помощью проверки подлинности Windows (и у вас нет/не помню учетные данные учетной записи sa). В этой ситуации вы можете воссоздать свою прошлую учетную запись пользователя из предыдущей установки Windows. Убедитесь, что эта новая учетная запись имеет тот же домен и имя пользователя, что и ваша предыдущая учетная запись. Войдите в систему через воссозданную учетную запись и предоставьте текущей (или “реальной” ) учетной записи пользователя достаточные разрешения (см. № 1 выше). После подтверждения того, что вы восстановили доступ, вы можете удалить обновленную учетную запись пользователя.

Ответ №6

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

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка crc что это такое
  • Ошибка cs0263 разделяемые объявления не должны указывать различные базовые классы