Related
I am using sqlcmd command line to connect to a database. I want to change the application name so that I can have multiple processes using sqlcmd, and be able to differentiate these processes from the server side. I know in SQL Server Management Studio I could do this (Change the Application Name of SSMS), but how can I do this in command line?
I checked the sqlcmd -?, but didn't find any useful parameter. There is another command line tool bcp, but I don't find any useful info there either.
The flag -H can be used to set "workstation_name".
It's is not the application name, but can serve the same purpose.
Use SELECT HOST_NAME() to get the value.
I am getting an error, While I am trying to connect (LocalDB)\MSSQLLocalDB through SQL Server management studio. I also tried to login with default database as master the error is same.
Here is the Server details.
Warning: this will delete all your databases located in MSSQLLocalDB. Proceed with caution.
The following command through sqllocaldb utility works for me.
sqllocaldb stop mssqllocaldb
sqllocaldb delete mssqllocaldb
sqllocaldb start "MSSQLLocalDB"
After that I restarted the sql server management studio, and it is successfully established connection through (LocalDB)\MSSQLLocalDB
For this particular error, what gave me access to my MDF in VS2019 was:
In Solution Explorer, right click your MDF file
Detach
That was it and I now have access. I was expecting to detach and attach, but that wasn't needed.
I also could not get to my (localdb) in SSMS either, so what helped me there was a solution by Leniel Maccaferri. Here is the link to his site, along with the excerpt that helped me:
https://www.leniel.net/2014/02/localdb-sqlserver-2012-cannot-open-database-requested-by-login-the-login-failed-error-4060.html
So guess what: the solution is ridiculously easy once you know what to do of course…
Click that Options >> button in Figure 1. Now select the Connection Properties tab.
SSMS Connect to Server | Connection Properties | Connect to database optionFigure 2 - SSMS Connect to Server | Connection Properties | Connect to database option
I had to type master in Connect to database field since I did not have it in the list of available databases.
Now click connect and you’re done.
I am starting to learn SQL and I have a book that provides a database to work on. These files below are in the directory but the problem is that when I run the query, it gives me this error:
Msg 5120, Level 16, State 101, Line 1 Unable to open the physical file
"C:\Murach\SQL Server 2008\Databases\AP.mdf". Operating system error
5: "5(Access is denied.)".
CREATE DATABASE AP
ON PRIMARY (FILENAME = 'C:\Murach\SQL Server 2008\Databases\AP.mdf')
LOG ON (FILENAME = 'C:\Murach\SQL Server 2008\Databases\AP_log.ldf')
FOR ATTACH
GO
In the book the author says it should work, but it is not working in my case. I searched but I do not know exactly what the problem is, so I posted this question.
SQL Server database engine service account must have permissions to read/write in the new folder.
Check out this
To fix, I did the following:
Added the Administrators Group to the file security permissions with
full control for the Data file (S:) and the Log File (T:).
Attached the database and it works fine.
An old post, but here is a step by step that worked for SQL Server 2014 running under windows 7:
Control Panel ->
System and Security ->
Administrative Tools ->
Services ->
Double Click SQL Server (SQLEXPRESS) -> right click, Properties
Select Log On Tab
Select "Local System Account" (the default was some obtuse Windows System account)
-> OK
right click, Stop
right click, Start
Voilá !
I think setting the logon account may have been an option in the installation, but if so it was not the default, and was easy to miss if you were not already aware of this issue.
To get around the access denied issue, I started SSMS as administrator and that allowed me to attach a database from my local drive. The database was created in another SQL and windows instance.
This is Windows related issue where SQL Server does not have the appropriate permission to the folder that contains .bak file and hence this error.
The easiest work around is to copy your .bak file to default SQL backup location which has all the necessary permissions. You do not need to fiddle with anything else. In SQL SERVER 2012, this location is
D:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Backup (SQL 2012)
C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Backup (SQL 2014)
C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\Backup (SQL 2016)
I had this problem. Just run SQL Server as administrator
Yes,It's right.The first you should find out your service account of sqlserver,you can see it in Task Manager when you press ctrl+alt+delete at the same time;Then,you must give the read/write privilege of "C:\Murach\SQL Server 2008\Databases" to the service account.
I solve this problem by adding Full control permission for both .mdf and .ldf files for Users group.
The problem is due to lack of permissions for SQL Server to access the mdf & ldf files. All these procedures will work :
you can directly change the MSSQLSERVER service startup user account, with the user account who have better privileges on the files. Then try to attach the database.
Or you can assign the user to the file in security tab of the mdf & ldf files properties with read and and write privileges checked.
Startup with windows administrator account, and open SQL Server with run as administrator option and try to login with windows authentication and now try to attach the database.
For me it was solved in the following way with SQL Server Management studio
-Log in as admin (I logged in as windows authentication)
-Attach the mdf file (right click Database | attach | Add )
-Log out as admin
-Log in as normal user
The actual server permissions will not matter at this point; all looks ok.
SQL Server itself needs folder permissions.
depending on your version, you can add SERVERNAME$MSSQLSERVER permissions to touch your folder. Othewise, it has to be in the default BACKUP directory (either where you installed it or default to c:\programfiles(x)\MSSQL\BACKUP.
Even if you do the following steps you COULD get the same error message.
1. login as SA user (SSMS)
2. Edit the file permissions to say "everyone" full access (windows folder)
3. Delete the Log file (Windows Exploring (this was what I had done per advise from some msdn forum)
I still GOT the permission error, but then I noticed that in the Attach screen, the bottom section STILL showed the LOG file, and the error message remained the same.
Hope this helps someone who did the same thing.
It means the SSMS login user does not have permission on the .mdf file. This is how it has worked for me:
I had opened the SSMS (Run as administrator) and login as an administrator user, database right-click attach, click add, select the .mdf file, click Ok. Done.
I had this issue when I try to backup a database.
System.Data.SqlClient.SqlError:
Cannot open backup device 'C:\x\x\xxx.bak'.
Operating system error 5 (Access is denied.). (Microsoft.SqlServer.Smo)
When I had this issue I thought that the user which I'm connecting to database don't have rights to access to the backup location. I gave full control to that user but nothing changed. This is because the service for SQL Server is running with another user.
At this point you may choose changing user of the service to local system account or add access rights for the current user of the service.
I choose the 2nd one.
After that change backup succeeded.
Very Simple Solution.
Login with System admin
copy your mdf and ldf files in "C:\Program Files (x86)\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA" Where all other data file recides.
Now attach from there it will work
I used Entity framework in my application and had this problem,I seted any permission in folders and windows services and not work,
after that I start my application as administrator (right click in exe file and select "run as admin") and that works fine.
If you get this error on an .MDF file in the APP_DATA folder (or where ever you put it) for a Visual Studio project, the way I did it was to simply copy permissions from the existing DATA folder here (I'm using SQL Express 2014 to support an older app):
C:\Program Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS2014\MSSQL\DATA
(note: your actual install path my vary - especially if your instance name is different)
Double click on theDATA folder first as administrator to make sure you have access, then open the properties on the folder and mimic the same for the APP_DATA folder. In my case the missing user was MSSQL$SQLEXPRESS2014 (because I named the instance SQLEXPRESS2014 - yours may be different). That also happens to be the SQL Server service username.
For some reason, setting all the correct permissions did not help in my case. I had a file db.bak that I was not able to restore due to the 5(Access is denied.) error. The file was placed in the same folder as several other backup files and all the permissions were identical to other files. I was able to restore all the other files except this db.bak file. I even tried to change the SQL Server service log on user — still the same result. I've tried copying the file with no effect.
Then I attempted to just create an identical file by executing
type db.bak > db2.bak
instead of copying the file. And voila it worked! db2.bak restored successfully.
I suspect that some other problems with reading the backup file may be erroniously reported as 5(Access is denied.) by MS SQL.
In linux, I went to /var/opt/mssql/data/ folder and opened a terminal with sudo then, changed my *.mdf and *.ldf file permissions as below in which you replace yourDB with your Database file name and myUser to currently logged username:
chmod 755 yourDB.mdf
chown myUser yourDB.mdf
chmod 755 yourDB.ldf
chown myUser yourDB.ldf
After that, it was reconnected without any issue.
If the database you are trying to attach is compressed it may show error message.
First you have to decompress the file. For that go to properties of mdf/ldf file >> then "Advanced" >> Uncheck "Compress Contents to save disk space" >> Press "Apply".
After that give it a try.
Run SQL Server management studio as Administrator
Log in as Windows user
Remove log file if you have only MDF file (haven't log file)
With 3 items in the above checklist, you will remove almost problems related with attach database task.
If you're using Storage Gateway - SMB (S3)
Do this from the management studio
EXEC xp_cmdshell 'net use X: \100.155.16.6\mystoragegatewayfolder xxmysuperpassxx /user:sgw-445577\smbguest /persistent:yes /y'
EXEC XP_CMDSHELL 'Dir X:' (this should show you the Directory info, serial no etc)
Mount the drive (This PC - > Mount network drive, using the same info above)
Test run a backup job using scheduled backup, this will force to use the sql server agent and you can see where it's writing and whats the issue if any.
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.
I have a instnwnd.sql which is a script file for northwind database installation. I don't know how to install this database. I have tried the procedure http://msdn.microsoft.com/en-us/library/ms227484(v=vs.90).aspx but I could not succeed. The error comes out to be "The user is not associated with a trusted sql server connection" I read some where u can do it using query analyser, but what is the sql statement for that ?? Somebody please help me.
Thanks in anticipation
To overcome the "sa" problem I used this and it worked for me.
C:\Users\UserName>sqlcmd -E -i c:\path\to\instnwnd.sql
The website I got this from is
Install Northwind Database.
When you followed the instructions from the MSDN page, and you ran
osql -U sa -P [password] -i instnwnd.sql
you did see the note about replacing [password] with the actual administrative password you created when you installed SQL Server, right?
Note For [password], type the system administrator password that you
created earlier.
Just open the instnwnd.sql file (which is plain text) in Notepad, copy all the text, and paste it into the query window in SQL Server Management Studio. Then press F5 to run the SQL script.