How do I grant myself admin access to a local SQL Server instance? - sql

I installed SQL Server 2008 R2 to my local machine. But, I can't create a new database because of rights (or lack of).
"CREATE DATABASE PERMISSION DENIED"
So, I tried to assign the admin privileges to my current login
"User does not have permission to perform this action."
I also tried to create a new login that would have admin privileges but with no luck. How do I grant myself admin rights so that I can create a database? I can re-install, but I prefer not to.

Open a command prompt window. If you have a default instance of SQL Server already running, run the following command on the command prompt to stop the SQL Server service:
net stop mssqlserver
Now go to the directory where SQL server is installed. The directory can for instance be one of these:
C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Binn
C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Binn
Figure out your MSSQL directory and CD into it as such:
CD C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Binn
Now run the following command to start SQL Server in single user mode. As
SQLCMD is being specified, only one SQLCMD connection can be made (from another command prompt window).
sqlservr -m"SQLCMD"
Now, open another command prompt window as the same user as the one that started SQL Server in single user mode above, and in it, run:
sqlcmd
And press enter. Now you can execute SQL statements against the SQL Server instance running in single user mode:
create login [<<DOMAIN\USERNAME>>] from windows;
-- For older versions of SQL Server:
EXEC sys.sp_addsrvrolemember #loginame = N'<<DOMAIN\USERNAME>>', #rolename = N'sysadmin';
-- For newer versions of SQL Server:
ALTER SERVER ROLE [sysadmin] ADD MEMBER [<<DOMAIN\USERNAME>>];
GO
Source.
UPDATED
Do not forget a semicolon after ALTER SERVER ROLE [sysadmin] ADD MEMBER [<<DOMAIN\USERNAME>>]; and do not add extra semicolon after GO or the command never executes.

Yes - it appears you forgot to add yourself to the sysadmin role when installing SQL Server. If you are a local administrator on your machine, this blog post can help you use SQLCMD to get your account into the SQL Server sysadmin group without having to reinstall. It's a bit of a security hole in SQL Server, if you ask me, but it'll help you out in this case.

I adopted a SQL 2012 database where I was not a sysadmin but was an administrator on the machine. I used SSMS with "Run as Administrator", added my NT account as a SQL login and set the server role to sysadmin. No problem.

Here's a script that claims to be able to fix this.
Get admin rights to your local SQL Server Express with this simple script
Download link to the script
Description
This command script allows you to easily add yourself to the sysadmin
role of a local SQL Server instance. You must be a member of the
Windows local Administrators group, or have access to the credentials
of a user who is. The script supports SQL Server 2005 and later.
The script is most useful if you are a developer trying to use SQL
Server 2008 Express that was installed by someone else. In this
situation you usually won't have admin rights to the SQL Server 2008
Express instance, since by default only the person installing SQL
Server 2008 is granted administrative privileges.
The user who installed SQL Server 2008 Express can use SQL Server
Management Studio to grant the necessary privileges to you. But what
if SQL Server Management Studio was not installed? Or worse if the
installing user is not available anymore?
This script fixes the problem in just a few clicks!
Note: You will need to provide the BAT file with an 'Instance Name' (Probably going to be 'MSSQLSERVER' - but it might not be): you can get the value by first running the following in the "Microsoft SQL Server Management Console":
SELECT ##servicename
Then copy the result to use when the BAT file prompts for 'SQL instance name'.
#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 /P sqlinstance=Enter SQL instance name, or default to SQLEXPRESS: ) else (set sqlinstance=%1)
if .%sqlinstance% == . (set sqlinstance=SQLEXPRESS)
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
pause

Microsoft has an article about this issue. It goes through it all step by step.
https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/connect-to-sql-server-when-system-administrators-are-locked-out
In short it involves starting up the instance of sqlserver with -m like all the other answers suggest. However Microsoft provides slightly more detailed instructions.
From the Start page, start SQL Server Management Studio. On the View menu, select Registered Servers. (If your server is not already
registered, right-click Local Server Groups, point to Tasks, and then
click Register Local Servers.)
In the Registered Servers area, right-click your server, and then
click SQL Server Configuration Manager. This should ask for permission
to run as administrator, and then open the Configuration Manager
program.
Close Management Studio.
In SQL Server Configuration Manager, in the left pane, select SQL
Server Services. In the right-pane, find your instance of SQL Server.
(The default instance of SQL Server includes (MSSQLSERVER) after the
computer name. Named instances appear in upper case with the same name
that they have in Registered Servers.) Right-click the instance of SQL
Server, and then click Properties.
On the Startup Parameters tab, in the Specify a startup parameter box,
type -m and then click Add. (That's a dash then lower case letter m.)
Note
For some earlier versions of SQL Server there is no Startup Parameters
tab. In that case, on the Advanced tab, double-click Startup
Parameters. The parameters open up in a very small window. Be careful
not to change any of the existing parameters. At the very end, add a
new parameter ;-m and then click OK. (That's a semi-colon then a dash
then lower case letter m.)
Click OK, and after the message to restart, right-click your server
name, and then click Restart.
After SQL Server has restarted your server will be in single-user
mode. Make sure that that SQL Server Agent is not running. If started,
it will take your only connection.
On the Windows 8 start screen, right-click the icon for Management
Studio. At the bottom of the screen, select Run as administrator.
(This will pass your administrator credentials to SSMS.)
Note
For earlier versions of Windows, the Run as administrator option
appears as a sub-menu.
In some configurations, SSMS will attempt to make several connections.
Multiple connections will fail because SQL Server is in single-user
mode. You can select one of the following actions to perform. Do one
of the following.
a) Connect with Object Explorer using Windows Authentication (which
includes your Administrator credentials). Expand Security, expand
Logins, and double-click your own login. On the Server Roles page,
select sysadmin, and then click OK.
b) Instead of connecting with Object Explorer, connect with a Query
Window using Windows Authentication (which includes your Administrator
credentials). (You can only connect this way if you did not connect
with Object Explorer.) Execute code such as the following to add a new
Windows Authentication login that is a member of the sysadmin fixed
server role. The following example adds a domain user named
CONTOSO\PatK.
CREATE LOGIN [CONTOSO\PatK] FROM WINDOWS; ALTER SERVER ROLE
sysadmin ADD MEMBER [CONTOSO\PatK];
c) If your SQL Server is running in
mixed authentication mode, connect with a Query Window using Windows
Authentication (which includes your Administrator credentials).
Execute code such as the following to create a new SQL Server
Authentication login that is a member of the sysadmin fixed server
role.
CREATE LOGIN TempLogin WITH PASSWORD = '************'; ALTER
SERVER ROLE sysadmin ADD MEMBER TempLogin;
Warning:
Replace ************ with a strong password.
d) If your SQL Server is running in mixed authentication mode and you
want to reset the password of the sa account, connect with a Query
Window using Windows Authentication (which includes your Administrator
credentials). Change the password of the sa account with the following
syntax.
ALTER LOGIN sa WITH PASSWORD = '************'; Warning
Replace ************ with a strong password.
The following steps now change SQL Server back to multi-user mode.
Close SSMS.
In SQL Server Configuration Manager, in the left pane, select SQL
Server Services. In the right-pane, right-click the instance of SQL
Server, and then click Properties.
On the Startup Parameters tab, in the Existing parameters box, select
-m and then click Remove.
Note
For some earlier versions of SQL Server there is no Startup Parameters
tab. In that case, on the Advanced tab, double-click Startup
Parameters. The parameters open up in a very small window. Remove the
;-m which you added earlier, and then click OK.
Right-click your server name, and then click Restart.
Now you should be able to connect normally with one of the accounts
which is now a member of the sysadmin fixed server role.

Its actually enough to add -m to startup parameters on Sql Server Configuration Manager, restart service, go to ssms an add checkbox sysadmin on your account, then remove -m restart again and use as usual.
Database Engine Service Startup Options
-m Starts an instance of SQL Server in single-user mode.

The other answers are lacking in visual screenshots, this is a concisely summarised version of Microsoft's docs,
Open Start Menu, right-click SQL Server Configuration Manager icon and choose Run as administrator.
Right-click the instance of SQL Server, and then select Properties.
Here we will setup SQL server to start in single-user mode.
On the Startup Parameters tab, add either,
a) Runs SQL server in single-user mode
-m
b) Runs SQL server in single-user mode + Allow unlimited connections through SSMS.
-m"Microsoft SQL Server Management Studio - Query"
I highly recommend (b). Without this, you can't even open Object Explorer and open a new query! Because that counts as 2 connections, and isn't allowed as we're running in single-user mode.
By appending the application name after the -m option, we allow unlimited connections through that application.
For some earlier versions of SQL Server there is no Startup Parameters tab. In that case, on the Advanced tab, double-click Startup Parameters. The parameters open up in a small window. Be careful not to change any of the existing parameters. At the very end, add a new parameter ;-m and then select OK. (That's a semi-colon then a dash then lower case letter m.)
Right-click your server name, and select Restart.
After SQL Server has restarted, your server will be in single-user mode. Make sure that SQL Server Agent isn't running. If started, it will take your only connection. Also disable SQL reporting services, analysis services, SSIS and everything else except for SQL server engine.
From the Windows Start menu, right-click Management Studio and select Run as administrator. This will pass your administrator credentials to SSMS.
a) Connect with Object Explorer. Expand Security, expand Logins, and right click your own login. On the Server Roles page, select sysadmin.
Close Management Studio.
These next few steps change SQL Server back to multi-user mode. We need to undo step (3) to (5).
In SQL Server Configuration Manager, in the right-pane, right-click the instance of SQL Server, and then select Properties.
On the Startup Parameters tab, in the Existing parameters box, select -m and then select Remove.
Restart SQL server services and reenable SQL server agent, Reporting Services etc. as required.
References,
Microsoft instructions
mssqltips - graphical tutorial

I removed on purpose my sysadmin permissions from MS SQL Server 2019 as I was testing a bug. I was able to regain them without reinstall using single-user mode and then logging as admin in SSMS. I am admin of this machine, otherwise it would not be possible.
Go to SQL Server 2019 Configuration Manager and stop the service for your SQL instance (node SQL Server Services-> SQL Server (yourinstancename))
From the properties (node SQL Server Services-> SQL Server (yourinstancename)-> Properties -> StartUp Parameters) enter -m, click Add and Apply buttons (You should have a row with these two symbols on it only -m in Existing parameters when you have finished)
Confirm with OK.
Start the stopped previously service.
Start SSMS as admin.
Add sysadmin permissions to my user (Security -> Logins -> New login -> Server roles).
Remove the additional -m startup parameter you added previously.
Restart the SQL Server service.
Reference:
https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/connect-to-sql-server-when-system-administrators-are-locked-out?view=sql-server-ver16

If you're looking to add a domain user, this script will save you some time.
--
-- 1) CREATE LOGIN domain\USERNAME
--
DECLARE #domain VARCHAR(MAX);
DECLARE #template VARCHAR(MAX)
DECLARE #sql VARCHAR(MAX)
SET #domain = DEFAULT_DOMAIN();
SET #template = 'CREATE LOGIN "{domain}\USERNAME" FROM WINDOWS WITH DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english]'
SET #sql = REPLACE(#template, '{domain}', #domain)
EXECUTE (#sql)
--
-- 2) GRANT SYSADMIN server level permission on domain\USERNAME
--
DECLARE #domain VARCHAR(MAX);
DECLARE #template VARCHAR(MAX)
DECLARE #sql VARCHAR(MAX)
SET #domain = DEFAULT_DOMAIN();
SET #template = 'EXEC sp_addsrvrolemember #loginame = N''{domain}\USERNAME '', #rolename = N''sysadmin'''
SET #sql = REPLACE(#template, '{domain}', #domain)
EXECUTE (#sql)
Simply replace the "USERNAME" with your own username. You don't have to enter the domain, as it will dynamically figure that out using DEFAULT_DOMAIN(). Fun fact: you can also use this to quickly add the same user, over multiple databases on different domains. Run this command using SSMS's "run query on multiple databases" feature.

Related

How to add username and password in sqllocaldb

I am going to start work on new Desktop application. There is I want to use light weight and standalone database so that I am going use SQL LocalDB but I want to add authentication. There I need username and password before accessing database but authentication not applied there please help me how can I do it.
If we cannot add username add password in SQL LocalDB then please suggest me any another database that will best for me and also I can use entity framework with that.
Thanks in advance
To add your new DB user to your MSSQLLocalDB you need to connect to it and execute this:
CREATE LOGIN your_user WITH PASSWORD = 'your_password';
CREATE USER your_user FOR LOGIN your_user;
EXEC sp_addrolemember 'db_owner', 'your_user'
Then you will be able to connect to MSSQLLocalDB database engine with SQL Server Authentication using these credentials.
Server name: (LocalDB)\MSSQLLocalDB
Authentication: SQL Server Authentication
User: your_user
Password: your_password
Or you can use instance pipe name instead of (LocalDB)\MSSQLLocalDB as a Server name (see below where to get it).
Initial connection to your local DB from SQL Server Management Studio (SSMS)
Initially to run the SQL command above you need to connect to your MSSQLLocalDB with Windows Authentication. You can do it in two ways (try the second if the first one won't work by default).
Using instance name
Server name: (LocalDB)\MSSQLLocalDB
Authentication: Windows Authentication
Using instance pipe name
From the command line go to C:\Program Files\Microsoft SQL Server\130\Tools\Binn\ (you might need to use other versions and replace \130\ with your folder name) and run SqlLocalDB.exe to find the local DB instances you have:
SqlLocalDB.exe i
Make sure you have MSSQLLocalDB listed. Then run this command to see the MSSQLLocalDB status (the first line) and start if it's stopped (the second line):
SqlLocalDB.exe i MSSQLLocalDB
SqlLocalDB.exe start MSSQLLocalDB
Then you can execute SqlLocalDB.exe i MSSQLLocalDB again to see the the instance pipe name. Something like this np:\\.\pipe\LOCALDB#D7900618\tsql\query
To connect in SSMS you need to enter:
Server name: np:\\.\pipe\LOCALDB#D7900618\tsql\query
Authentication: Windows Authentication
just want to add you need sysadmin role so you can create databases
using this code
ALTER SERVER ROLE sysadmin ADD MEMBER your_user;
GO
use this :
SqlConnection con = new SqlConnection("Server= localhost, Authentication=Windows Authentication, Database= employeedetails");
con.Open();
if you want sql server authentication than read this :
http://msdn.microsoft.com/en-us/library/ms162132.aspx

Sysadmin and sa in sql server 2000 - drop and recreate login?

A somewhat open-ended question so any information that closes the gaps in my knowledge would be appreciated.
When doing a SQL Server upgrade from 2000 to 2008 the upgrade advisor can give the following warning:
The Upgrade Advisor detected one or more user-defined login names that match the names of fixed server roles. Fixed server role names are reserved in SQL Server 2008. Rename the login before upgrading to SQL Server 2008.
I believe this is because say for example a login of 'sysadmin' in a sql server 2000 database will clash with a fixed server role of 'sysadmin' in 2008..
Is there a way to safely drop and re-create these logins or could dropping a login of say 'sa' have unintended consequences?
Repro of issue :
1) Delete the Builtin/administrator account .
2) Try to connect to SQL Server through sqlcmd or Management studio .You will get the error 18456 Level 14 State 1.
3) Assume that i have forgotten the SA password as well.
Solution:
1) Login to the server using administrator account .
2) Stop SQL Server service and start it with -m switch(single user mode) .
2) Type sqlcmd -E and hit enter .If its named instance then sqlcmd -S -E and hit enter.
4) You will see > sign
5) Commands you need to use
CREATE LOGIN [BUILTIN\Administrators] FROM WINDOWS WITH DEFAULT_DATABASE= [master], DEFAULT_LANGUAGE=[us_english]
go
6) Give sysadmin role to the login we just created
EXEC master..sp_addsrvrolemember #loginame = N'BUILTIN\Administrators', #rolename = N'sysadmin'
GO
7) You are done.Exit out of it .8) restart you SQL Server service without -m parameter.
You are done .Login again to SQL Server and reset the SA password .Save the SA password for the rainy day .
Source

sql server 2012: cannot alter the login sa

I'm trying to create a database on my local machine using SSMS version 11.0.2100.60. I've run the application as administrator, logged in using Windows authentication, and I've added MYDOMAIN\my-username to the Logins. However if I try to create a db with this login I get the message
CREATE DATABASE permission denied in database 'master'.
(Microsoft SQL Server, Error: 262)
If I try to add the privelage dbcreator to my user, I get the following error.
User does not have permission to perform this action.
(Microsoft SQL Server, Error: 15247)
I can't log in as sa as I don't know/remember the password (is there a preset default?), and if I try to change the password I get the message:
Cannot alter the login 'sa', because it does not exist or you do not have permission.
(Microsoft SQL Server, Error: 15151)
Finally I note that the account 'sa' is disabled, and if I try to enable it I get the same error as before. Is there any way around this or do I need to re-install?
Version info:
Microsoft SQL Server Management Studio 11.0.2100.60
Microsoft Analysis Services Client Tools 11.0.2100.60
Microsoft Data Access Components (MDAC) 6.2.9200.16384
Microsoft MSXML 3.0 4.0 6.0
Microsoft Internet Explorer 9.10.9200.16635
Microsoft .NET Framework 4.0.30319.18051
Operating System 6.2.9200
I found the answer here:
In order to start SQL Server in single-user mode, you can add the
parameter “-m” at the command line. You can also use the SQL Server
Configuration Manager tool, which provides proper controls for the
file access and other privileges. To use the Configuration Manager
tool to recover your system, use the following steps:
Open the Configuration Manager tool from the "SQL Server 2005| Configuration" menu
Stop the SQL Server Instance you need to recover
Navigate to the “Advanced” tab, and in the Properties text box add “;–m” to the end of the list in the “Startup parameters” option
Click the “OK” button and restart the SQL Server Instance
A little more specific :
Open Sql Configuration Manager.
Select SQL Server Services.
On the right hand side, select the instance.
Right click on it and open properties.
In the advanced tab attach ";-m" at the end of the Startup Parameters field.
Apply and restart the service.
Now you have privilege to enable "sa" user and modify its password.
once done, remove ";-m" and restart the service.
You are good to go.
I'd like to point out an alternative answer laid out on DBA SE. Download PSExec onto the box that is having the problem and follow the instructions laid out in this blog post to effortlessly change admin settings using the NT Authority\System account.
./psexec -s -i "C:\...\Ssms.exe"
Wanted to share this solution as it solved my problem!

SQL Server 2008 Error 233

I'm creating new login in SQL Server 2008 with following sql script:
CREATE LOGIN [xyz] WITH PASSWORD='xyz',
DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english],
CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
It creates new login successfully. But when I try to login with it using SQL Server Management Studio it fails saying:
A connection was successfully established with the server, but then an error occurred during the login process. (provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.) (Microsoft SQL Server, Error: 233)
What's wrong? How do I solve this issue?
Here is how I done it, maybe it works for you too.
login Microsoft SQL Server 2012 with windows authentication.
right-click onto the server name in Object Explorer and click Properties
In the new tab click Security
select SQL Server and Windows Authentication
Ok
Close the SQL server management studio.
start+run
write services.msc
search for SQL there and restart all services.
that works for me.
It's also possible that you're trying to use SQL Server Authentication without having enabled it. To fix this, right-click Properties on your server instance in SQL Server Management Studio, and update the security settings to include "SQL Server and Windows Authentication mode".
Looks like you're trying to connect using named pipes, but SQL Server is not listening on that protocol. See MSDN.
The two fixes MSDN suggests are:
Connect using TCP/IP, or use the SQL
Server Configuration Manager to
enable remote connections using named
pipes.
Using SQL Server Configuration
Manager on the client computer, move
TCP before named pipes in the
protocol order list.
I had a similar issue:
1. log in as the master user or windows authenticated user.
2. right click on the database --> properties --> security -->
3. change Windows Authentication mode to "SQL server and windows authentication mode" by clicking on the radio button. (if it is not)
4. restart the server
I had the same issue when i first setup SQL Server 2014 on my local machine.
In my case the solution was to set a correct defualt database.
Login with Administrator in SQL Server
Go to Securities >> Logins >> select your user name and go to properties
From Status >> uncheck user account lock check box
Change password for the user
Restart the sql server and login with your username.
I was facing the same error.
I've resolved the error by following below mentioned steps:
Disable named pipes and restart sql services.
After restart sql server I enabled names pipes and did a sql server restart again (Link for Step 1 and 2)
Connect to SQL server via studio.
Right click on SQL instance --> Properties --> Connections --> "Set the Maximum number of 5. concurrent connections to '0' ".
Save the change.
Restart the SQL server if possible. (Link for step 3 to 6)
I hope this will help someone
This is might not be a connection issue . Check your default database and if that is online . More commonly this issues seen when the default database will be offline or not exists . If your default database other than master ,better check this option.
I got a way to go around the problem.
Open one instance and login using the windows authentication
allow sql and windows auth both by right cliking on the db server.
Open second instance and login using sql authentication.
bingo the sql authenticated instance open .. :)
Actually in this way we cheat the sql authenticated instance as it tries to find an already running instance.. worked fr me.. good luck
I tried most of the solution but was not able to solve it until I found this URL which says to do the following:
Open SQL Server Management Studio and run the these queries:
sp_configure 'show advanced options', 1;
go
reconfigure
go
sp_configure 'user connections', 0
go
reconfigure
go
The reason why we got this error is that the user connections was reset to 1, so only one user was able to connect with the SQL server.
just a simple query worked for. I hope this will work for others as well.
I have not used the script style, but login through GUI I encountered the same error code. I had entered wrong user name and this is why I was getting the Sql Server, Error: 233. In order to resolve this, you should input the following information:
Server Name: MachineName\SQLEXPRESS
Authentication: SqlServer Authentication
User Name: Assigned user-name or simply sa
Password: xyzpqr
NOTE: Here I have wrote above data for demo purpose only, actual data is your machine & software's properties.
According to: https://msdn.microsoft.com/en-us/library/bb326280.aspx
Go to --> Remot setting
Go to "Remote" tab
in "Remote Assistance", Tick "Allow Remote Assistance connection to this computer", Click the "Advance" button and tick the "Allow..." and in the "Invitation" set the "30 days"
Then in the "Remote Desktop" part
Just tick "Allow remote connection to this computer"
After following the examples here and still not getting in, I found that my sa login was disabled. The following got me in:
Logged back in under windows authentication.
Expanded Security Tab
Expanded Logins Tab
Right-clicked sa and selected Properties
Went to the Status Tab
Under Login: Clicked 'Enabled' radio
Restarted Server and logged in as sa.
This assumes you have set sa password already using
ALTER LOGIN sa WITH PASSWORD = '<enterStrongPasswordHere>' ;
"A connection was successfully established with the server, but then an error occurred during the login process."
I was getting this problem from sqllocaldb when used from within Docker. The problem was the Docker image was not allocated enough memory. Increasing the memory actually fixed the problem.

SQL Server Script to create a new user

I want to write a script to create a admin user ( with abcd password ) in SQL Server Express.
Also I want to assign this user admin full rights.
Based on your question, I think that you may be a bit confused about the difference between a User and a Login. A Login is an account on the SQL Server as a whole - someone who is able to log in to the server and who has a password. A User is a Login with access to a specific database.
Creating a Login is easy and must (obviously) be done before creating a User account for the login in a specific database:
CREATE LOGIN NewAdminName WITH PASSWORD = 'ABCD'
GO
Here is how you create a User with db_owner privileges using the Login you just declared:
Use YourDatabase;
GO
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'NewAdminName')
BEGIN
CREATE USER [NewAdminName] FOR LOGIN [NewAdminName]
EXEC sp_addrolemember N'db_owner', N'NewAdminName'
END;
GO
Now, Logins are a bit more fluid than I make it seem above. For example, a Login account is automatically created (in most SQL Server installations) for the Windows Administrator account when the database is installed. In most situations, I just use that when I am administering a database (it has all privileges).
However, if you are going to be accessing the SQL Server from an application, then you will want to set the server up for "Mixed Mode" (both Windows and SQL logins) and create a Login as shown above. You'll then "GRANT" priviliges to that SQL Login based on what is needed for your app. See here for more information.
UPDATE: Aaron points out the use of the sp_addsrvrolemember to assign a prepared role to your login account. This is a good idea - faster and easier than manually granting privileges. If you google it you'll see plenty of links. However, you must still understand the distinction between a login and a user.
Full admin rights for the whole server, or a specific database? I think the others answered for a database, but for the server:
USE [master];
GO
CREATE LOGIN MyNewAdminUser
WITH PASSWORD = N'abcd',
CHECK_POLICY = OFF,
CHECK_EXPIRATION = OFF;
GO
EXEC sp_addsrvrolemember
#loginame = N'MyNewAdminUser',
#rolename = N'sysadmin';
You may need to leave off the CHECK_ parameters depending on what version of SQL Server Express you are using (it is almost always useful to include this information in your question).
You can use:
CREATE LOGIN <login name> WITH PASSWORD = '<password>' ; GO
To create the login (See here for more details).
Then you may need to use:
CREATE USER user_name
To create the user associated with the login for the specific database you want to grant them access too.
(See here for details)
You can also use:
GRANT permission [ ,...n ] ON SCHEMA :: schema_name
To set up the permissions for the schema's that you assigned the users to.
(See here for details)
Two other commands you might find useful are ALTER USER and ALTER LOGIN.
If you want to create a generic script you can do it with an Execute statement with a Replace with your username and database name
Declare #userName as varchar(50);
Declare #defaultDataBaseName as varchar(50);
Declare #LoginCreationScript as varchar(max);
Declare #UserCreationScript as varchar(max);
Declare #TempUserCreationScript as varchar(max);
set #defaultDataBaseName = 'data1';
set #userName = 'domain\userName';
set #LoginCreationScript ='CREATE LOGIN [{userName}]
FROM WINDOWS
WITH DEFAULT_DATABASE ={dataBaseName}'
set #UserCreationScript ='
USE {dataBaseName}
CREATE User [{userName}] for LOGIN [{userName}];
EXEC sp_addrolemember ''db_datareader'', ''{userName}'';
EXEC sp_addrolemember ''db_datawriter'', ''{userName}'';
Grant Execute on Schema :: dbo TO [{userName}];'
/*Login creation*/
set #LoginCreationScript=Replace(Replace(#LoginCreationScript, '{userName}', #userName), '{dataBaseName}', #defaultDataBaseName)
set #UserCreationScript =Replace(#UserCreationScript, '{userName}', #userName)
Execute(#LoginCreationScript)
/*User creation and role assignment*/
set #TempUserCreationScript =Replace(#UserCreationScript, '{dataBaseName}', #defaultDataBaseName)
Execute(#TempUserCreationScript)
set #TempUserCreationScript =Replace(#UserCreationScript, '{dataBaseName}', 'db2')
Execute(#TempUserCreationScript)
set #TempUserCreationScript =Replace(#UserCreationScript, '{dataBaseName}', 'db3')
Execute(#TempUserCreationScript)
CREATE LOGIN AdminLOGIN WITH PASSWORD = 'pass'
GO
Use MyDatabase;
GO
IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'AdminLOGIN')
BEGIN
CREATE USER [AdminLOGIN] FOR LOGIN [AdminLOGIN]
EXEC sp_addrolemember N'db_owner', N'AdminLOGIN'
EXEC master..sp_addsrvrolemember #loginame = N'adminlogin', #rolename = N'sysadmin'
END;
GO
this full help you for network using:
1- Right-click on SQL Server instance at root of Object Explorer, click on Properties
Select Security from the left pane.
2- Select the SQL Server and Windows Authentication mode radio button, and click OK.
3- Right-click on the SQL Server instance, select Restart (alternatively, open up Services and restart the SQL Server service).
4- Close sql server application and reopen it
5- open 'SQL Server Configuration Manager' and tcp enabled for network
6-Double-click the TCP/IP protocol, go to the IP Addresses tab and scroll down to the IPAll section.
7-Specify the 1433 in the TCP Port field (or another port if 1433 is used by another MSSQL Server) and press the OK
8-Open in Sql Server: Security And Login And Right Click on Login Name And Select Peroperties And Select Server Roles And
Checked The Sysadmin And Bulkadmin then Ok.
9-firewall: Open cmd as administrator and type:
netsh firewall set portopening protocol = TCP port = 1433 name = SQLPort mode = ENABLE scope = SUBNET profile = CURRENT
This past week I installed Microsoft SQL Server 2014 Developer Edition on my dev box, and immediately ran into a problem I had never seen before.
I’ve installed various versions of SQL Server countless times, and it is usually a painless procedure. Install the server, run the Management Console, it’s that simple. However, after completing this installation, when I tried to log in to the server using SSMS, I got an error like the one below:
SQL Server login error 18456
“Login failed for user… (Microsoft SQL Server, Error: 18456)”
I’m used to seeing this error if I typed the wrong password when logging in – but that’s only if I’m using mixed mode (Windows and SQL Authentication). In this case, the server was set up with Windows Authentication only, and the user account was my own. I’m still not sure why it didn’t add my user to the SYSADMIN role during setup; perhaps I missed a step and forgot to add it. At any rate, not all hope was lost.
The way to fix this, if you cannot log on with any other account to SQL Server, is to add your network login through a command line interface. For this to work, you need to be an Administrator on Windows for the PC that you’re logged onto.
Stop the MSSQL service.
Open a Command Prompt using Run As Administrator.
Change to the folder that holds the SQL Server EXE file; the default for SQL Server 2014 is “C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Binn”.
Run the following command: “sqlservr.exe –m”. This will start SQL Server in single-user mode.
While leaving this Command Prompt open, open another one, repeating steps 2 and 3.
In the second Command Prompt window, run “SQLCMD –S Server_Name\Instance_Name”
In this window, run the following lines, pressing Enter after each one:
1
CREATE LOGIN [domainName\loginName] FROM WINDOWS
2
GO
3
SP_ADDSRVROLEMEMBER 'LOGIN_NAME','SYSADMIN'
4
GO
Use CTRL+C to end both processes in the Command Prompt windows; you will be prompted to press Y to end the SQL Server process.
Restart the MSSQL service.
That’s it! You should now be able to log in using your network login.