- Download the script from this Microsoft Site
- Run it as Administrator
- 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:\\.\pipe\SQLLocal\%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
- Download the script from this Microsoft Site
- Run it as Administrator
- 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:\\.\pipe\SQLLocal\%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
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!
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.AliM.Ali
1,9309 gold badges27 silver badges38 bronze badges
1
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
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
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
- Remove From My Forums
-
Question
-
hi
I have installed new SQLServer2012 instance and my domain user have sysadmin priviliges on this instance.
i have a restore procedure and it will execute WITH EXECUTE AS ‘domain\my username’, for all the devleopers have exec permissions to this procedure. But newly installed server this procedure was failing with the following message. But the same procedure
executing fine on other servers.Please suggest me to resolve this issue, Thanks in Advance!!
Msg 262, Level 14, State 1, Line 1
CREATE DATABASE permission denied in database ‘master’.
Msg 3013, Level 16, State 1, Line 1
RESTORE DATABASE is terminating abnormally.Thanks
Surendra
Answers
-
Thanks for all your support.
This issue occurring on my environment because the TRUSTWORTHY is false for the database where i am running the procedure. because of the this i am getting this issue.
once again thanks for all your support.
Thanks
Surendra
-
Marked as answer by
Friday, October 30, 2015 5:24 AM
-
Marked as answer by
[Решено] При создании БД выскочила ошибка — Разрешение 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 5 лет назад 2 times by Денис
Денис
(@denov)
Admin
| 122 Сообщения
0 94 1


