I need to create an SQL User: and came across this script:
CREATE USER [Username] FOR LOGIN [Domain\Username]
EXEC sp_addrolemember N'DatabaseRole', N'Username'
at this link:
Creating a user, mapping to a database and assigning roles to that database using SQL scripts
Can someone explain this script to me:
what is [Domain\Username]?
[Username] = The userName I want,
what is sp_addrolemember?
What is N'DatabaseRole',?
What shall I put as N'Username'? The username same as [Username]?
1: [Domain\Username] is for the windows Active Directory-user for that domain.
Example: Say you have an AD/Domain/Computer called StackOverFlow, that would be the Domain, and then your username is Awan, that makes it StackOverFlow\Awan
2: Correct, this is the username you want you just insert your username there (within the brackets)
Example [Awan]
3: sp_addrolemember is a function that adds the user with a specific role. (dbo and such)
4: N'DatabaseRole' is a numeric text where you write in what role your user is supposed to have. An example is db_owner, which makes the user able to create tables, delete tables, alter tables, and so on.
5: Exactly, you just put for example N'Awan' instead of N'Username'
Otherwise you can create a user from SSMS ( http://msdn.microsoft.com/en-us/library/aa337562.aspx )
As you are using WINDOWS server you can only create user for users who have access on windows server.
SERVERNAME\USERNAME E.g. TEMP_SERVER\Ashutosh
Uknow this
This Sp is basically sets roles for a user.
4&5. http://msdn.microsoft.com/en-us/library/ms187750.aspx
Below is a way to do it in GUI
http://msdn.microsoft.com/en-us/library/aa337562.aspx
Regards
Ashutosh Arya
[Domain\Username] is a format of windows authentication logon name; you use it to log on to things, one of them is SQL Server
[Username] = The userName I want - I hope so, it should exist on your domain, or if Domain is computer name, then it has to exist on your computer
sp_addrolemember is a stored procedure that assigns a role to your user; roles can be e.g. database level roles like db_owner, db_datareader, db_datawriter...
Look at 3.
If I have user MyUser on MyComputer, I would put MyComputer\MyUser; If I have user MyUser on MyDomain, I would put MyDomain\MyUser
Related
I try to map my other DB to a user by going to Security > Logins > right click someuser > Properties > User Mapping > Select DB > set as db_owner and then ok, but I keep on getting an error saying
User, group, or role 'someuser' already exists in the current database. (Microsoft SQL Server, Error: 15023)
What is causing the error, and how do I map that user to the database?
To fix the user and login mapping you need to open a query window in the SQL Server Management Studio. Enter the following two lines and replace myDB with the database name and myUser with the correct user name:
USE myDB
EXEC sp_change_users_login 'Auto_Fix', 'myUser'
If run successfully you should get an output like this one:
The row for user '****' will be fixed by updating its login link to a login already in existence.
The number of orphaned users fixed by updating users was 1.
The number of orphaned users fixed by adding new logins and then updating users was 0.**
Your user should now be mapped correctly.
Edit:
New way to Resolve/Fix an Orphaned User:
In the master database, use the CREATE LOGIN statement with the SID option to recreate a missing login, providing the SID of the database user.
CREATE LOGIN <login_name>
WITH PASSWORD = '<use_a_strong_password_here>',
SID = <SID>;
To map an orphaned user to a login which already exists in master, execute the ALTER USER statement in the user database, specifying the login name.
ALTER USER <user_name> WITH Login = <login_name>;
When you recreate a missing login, the user can access the database using the password provided. Then the user can alter the password of the login account by using the ALTER LOGIN statement.
ALTER LOGIN <login_name> WITH PASSWORD = '<enterStrongPasswordHere>';
if it is just one or two users, then easiest way is to drop the database user from the restored database, remap the database user to the server login using SSMS. If the server login does not exist then just create it, map the user.
Option 2: If you are migrating a large number of users, use sp_help_revlogin. sp_help_revlogin is a Microsoft supplied stored procedure that will help migrate logins from one server to another, including passwords and SIDs. Here is a good article about it SP_HELP_REVLOGIN : http://www.databasejournal.com/features/mssql/article.php/2228611/Migrating-Logins-from-One-SQL-Server-to-Another.htm
Code patches to help use it :
run following T-SQL Query in Query Analyzer. This will return all the existing users in database in result pan.
USE YourDB
GO
EXEC sp_change_users_login 'Report'
GO
Run following T-SQL Query in Query Analyzer to associate login with the username. ‘Auto_Fix’ attribute will create the user in SQL Server instance if it does not exist. In following example ‘ColdFusion’ is UserName, ‘cf’ is Password. Auto-Fix links a user entry in the sysusers table in the current database to a login of the same name in sysxlogins.
USE YourDB
GO
EXEC sp_change_users_login 'Auto_Fix', 'ColdFusion', NULL, 'cf'
GO
Run following T-SQL Query in Query Analyzer to associate login with the username. ‘Update_One’ links the specified user in the current database to login. login must already exist. user and login must be specified. password must be NULL or not specified
USE YourDB
GO
EXEC sp_change_users_login 'update_one', 'ColdFusion', 'ColdFusion'
GO
2) If login account has permission to drop other users, run following T-SQL in Query Analyzer. This will drop the user.
USE YourDB
GO
EXEC sp_dropuser 'ColdFusion'
GO
Create the same user again in the database without any error.
If you assign permissions to a database user without mapping it to the database first, it throws the error you mentioned.
You should be able to delete the user, map it to the database and then assign the user to the db_owner role.
First drop your user, then execute the script below:
USE [YOURDB]
GO
CREATE USER [USERNAME] FOR LOGIN [USERNAME]
GO
USE [YOURDB]
GO
ALTER USER [USERNAME] WITH DEFAULT_SCHEMA=[dbo]
GO
I had the problem when I was trying to copy a production database to a local test database. In SSMS, I made sure to disconnect from the production server before executing scripts on the local. However, even though I thought I had disconnected, someone pointed out that the title of the production database was still there, and I got errors that objects were already there. The solution was to totally exit from SSMS and start it again, only connecting to the local test database that time.
you can solve problem by expand database ->Security -> Users
and delete the user 'someuser' ,after that go to user mapping and assign.
this problem happen some times because the database user 'someuser' was deleted from 'Logins' in Security section in SSMS and the database still own this user
Create failed for User (Microsoft.SqlServer.Smo)
SQL Server Error User, group, or role already exists in the current database. (Microsoft SQL Server, Error: 15023)
To fix above error delete user under each database individually
I am having trouble granting permissions to users of my database. For instance, I cannot seem to get my user SELECT privileges no matter how many securables and memberships I give it. I started by giving the user select permission database>security>Users>Properties>securables
and giving it db_datareader membership. After this did not work I added the user to all of the memberships and granted him all permissions available in the securables section. After that failed, I gave the user all permissions available in the security>login>properties, I added the login to all server roles accept sysadmin and gave the user ownership of all schemas in the database I want him to access. Still I get this same error below:
The SELECT permission was denied on object 'Patient_Information', database 'Clinical_Data', schema 'dbo'
When I add the login to the role sysadmin, the user that it is mapped to has no problem doing selects, inserts and basically anything else. The weird thing is that when I look into database>properties>Permissions the user does not have any of the permissions that I have granted him in the securables section. Here is the code I use to grant:
USE Clinical_Data; GRANT Select on schema::DBO to lab31
Thanks in advance for any help you can provide.
I usually create a database role and assign the user to the role. Assign the schema privileges to the database roles. A quick example of this using code for a fictitious database is below.
--
-- 1 - GRANTING CORRECT USER ACCESS BY SCHEMA
--
--create test user login
CREATE LOGIN [User1] WITH PASSWORD=N'p#55w0rd'
GO
-- Make sure we are in autos
USE [AUTOS]
GO
--create user in test database
CREATE USER [User1] FOR LOGIN [User1] WITH DEFAULT_SCHEMA=[ACTIVE]
GO
--create role
CREATE ROLE [Auto_User] AUTHORIZATION [dbo]
GO
--apply permissions to schemas
GRANT ALTER ON SCHEMA::[ACTIVE] TO [Auto_User]
GO
GRANT CONTROL ON SCHEMA::[ACTIVE] TO [Auto_User]
GO
GRANT SELECT ON SCHEMA::[ACTIVE] TO [Auto_User]
GO
--ensure role membership is correct
EXEC sp_addrolemember N'Auto_User', N'User1'
GO
If you are more comfortable with SQL Server Management Studio, here is a go. All actions might not be exact but I did check them with SS 2012.
Lets say your login is [bilbo] and the database they want to access is [middle earth].
Is the default database for the server login = [bilbo] the database they are trying to query, [middle earth]?
[SMSS object explorer path]: Server -> security -> logins -> right click + properties
Is the server login mapped to a database user named [bilbo] in the [middle earth] database?
[SMSS object explorer path]: Database name -> security -> users
Make sure the user [bilbo] is not in any deny database roles (db_denydatareader, db_denydatawriter). Any deny actions over ride any grants.
[SMSS object explorer path]: Database name -> security -> roles -> database roles -> select + right click + properties
{You would add your custom database role here.}
Make sure the user [bilbo] has permissions to the schema.
[SMSS object explorer path]: Database name -> security -> schemas -> select + right click + properties
This should give you the layout of the land.
Find the offending revoke or lack of permission and assign it.
Please do not give out all server roles or all database roles! You are just asking for a head ache when the user does something stupid like drop table.
I am creating a new read/write user on SQL Azure as follows:
-- Connected to master
create login [fred] with password = 'xxx';
-- Connected to my DB
create user [fred] from login fred;
EXEC sp_addrolemember 'db_datareader', 'fred';
EXEC sp_addrolemember 'db_datawriter', 'fred';
When I login using SSMS I get an error saying Cannot open database "master" requested by the login. The login failed.
What am I doing wrong or missing?
By default, SSMS tries to connect to master, but your new account does not have access to master; only the user database I presume.
On the login screen of SSMS, you need to specify the database name as well; just click on the Options >> icon, which opens up the Connection Properties tab. In there, specify the database name you are trying to connect to.
After creating the database user in the specific database Database1,
again select 'master' and create database user.
Execute below statement twice - one for Database1 and another for 'master'
CREATE USER appuser1 FROM LOGIN appuser1;
Unfortunately, this is not documented in Azure help
https://learn.microsoft.com/en-gb/azure/azure-sql/database/logins-create-manage
--> Open new query window for master database and execute this commands
CREATE LOGIN AppLogin WITH password='XXXXXX'
GO
CREATE USER [AppUser] FOR LOGIN [AppLogin] WITH DEFAULT_SCHEMA=[dbo]
GO
--> Open new query window for YOUR Database
CREATE USER [AppUser] FOR LOGIN [AppLogin] WITH DEFAULT_SCHEMA=[dbo]
GO
EXEC sp_addrolemember 'db_owner', 'AppUser';
GO
Source: How to create custom user login for Azure SQL Database
As Karol commented in Herve Roggero's response, I had the same problem even after selecting the database.
In our case the problem was that the users we created in our databases were disabled.
After we run the following script in the database we wanted to connect for each user:
GRANT CONNECT TO [ourDbUser]
We refreshed the database's users and now they were enabled, and then we were able to connect to the database successfully.
For me, the issue was that the person who created the user on the database did so without specifying FROM LOGIN, therefore the user was available in the Security->Users tab, but login was still not possible. I had to recreate the user and linking it to the login with the same name on the database:
DROP USER [myuser]
GO
CREATE USER [myuser] FROM LOGIN [myuser] WITH DEFAULT_SCHEMA=[dbo]
GO
and then granting the correct permissions on the database, in my case:
ALTER ROLE db_datareader ADD MEMBER [myuser]
ALTER ROLE db_datawriter ADD MEMBER [myuser]
Two other reasons that can trip you up:
The Server Login and the Database User must be the same. You cannot have APILogin link to APIUser, Azure just doesn't like it
Hyphens aren't allowed in usernames on Azure, so you can't have API-User
I've done this before but not through scripts. I've to create a new user in SQL server (SQL Authentication) and map the user to a database and assign the roles for the user to that database using SQL scripts.
How can I do it?
Try:
CREATE USER [Username] FOR LOGIN [Domain\Username]
EXEC sp_addrolemember N'DatabaseRole', N'Username'
Obviously changing Username, and Domain\Username and the database role to being the username that you wish to grant rights to and the level of access, such as 'db_datareader'
The above solution works for me. However if the Username doesnt yet exist in that database as a USER, that username will not be fully mapped to the database role.
In this situation I first add the user:
USE databasename
CREATE USER [DOMAIN\svce_name] FOR LOGIN [DOMAIN\svce_name] WITH DEFAULT_SCHEMA=[dbo]
GO
Then I add the role:
USE databasename
EXEC sp_addrolemember N'db_ssisoperator', N'DOMAIN\svce_name'
GO
I have a Database say TestDatabase.I have already added an user under
NTAuthority\SYSTEM(Role) Db_owner.
Again i wish to add another user to the same Database under NTAuthority\System with
different role.
I received the following error :
The login already has an accoind under different username.
SQL Server Error :15063
How can i add different users to the same database with different role.
I would appreciate if i receive elobarate explanation.
You can't. You add the same user to multiple roles.
db_owner already has all rights anyway withing the database so any other permissions are superfluous.
CREATE USER [NTAuthority\SYSTEM] FROM LOGIN [NTAuthority\SYSTEM];
EXEC sp_addrolemember 'db_owner', 'NTAuthority\SYSTEM'
-- ...and fails
CREATE USER [bob] FROM LOGIN [NTAuthority\SYSTEM];
--Normally, for one user in multiple roles
EXEC sp_addrolemember 'DoStuff', 'NTAuthority\SYSTEM'
EXEC sp_addrolemember 'DoSpecialStuff', 'NTAuthority\SYSTEM'
--... and for another user
EXEC sp_addrolemember 'DoStuff', 'AnotherUser'
--... and for yet another user
EXEC sp_addrolemember 'DoLimitedStuff', 'TheThirdUser'
Edit:
Look at the MS documentation: Database-Level Roles and the parent Identity and Access Control topic
if is db_owner there is no point in adding him to any other role.
to add an existing user to a new role you run sp_roleaddmember