debugsqlMinor
Getting Msg 15151, Cannot alter the user 'xxxx', because it does not exist or you do not have permission
Viewed 0 times
cannotthemsgyouuserpermissiongetting15151existbecause
Problem
I have the following script and I keep getting errors when it is executed.
I have tried several permutations of this script with no success. It does create the login but won't let me alter the "user" or "role" properties. When I can get it to work with no errors, it does not make the changes to the user profile.
USE [master]
GO
If Not EXISTS (Select loginname from [master].[dbo].[syslogins]
Where name = 'xxxx' and dbname = 'xxxx-xxxx')
BEGIN
CREATE LOGIN [xxxx] WITH PASSWORD=N'xxxxx', DEFAULT_DATABASE=[xxxx-xxxx], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
ALTER LOGIN [xxxx] ENABLE
END
GO
USE [xxxx-xxxx]
ALTER USER [xxxx] WITH DEFAULT_SCHEMA=[db_datareader]
ALTER ROLE [db_datareader] ADD MEMBER [xxxx]
ALTER ROLE [db_datawriter] ADD MEMBER [xxxx]
ALTER ROLE [db_owner] ADD MEMBER [xxxx]
GOI have tried several permutations of this script with no success. It does create the login but won't let me alter the "user" or "role" properties. When I can get it to work with no errors, it does not make the changes to the user profile.
Solution
You are missing create user before you alter it.
Login - gets you entry to the server
Database User - gets you entry to a particular database
so in your script, add
few things :
Login - gets you entry to the server
Database User - gets you entry to a particular database
so in your script, add
create user from login ...USE [xxxx-xxxx]
create user [xxxx] from login [xxxx] <--- this is needed !
ALTER USER [xxxx] WITH DEFAULT_SCHEMA=[db_datareader]
ALTER ROLE [db_datareader] ADD MEMBER [xxxx]
ALTER ROLE [db_datawriter] ADD MEMBER [xxxx]
ALTER ROLE [db_owner] ADD MEMBER [xxxx]
GOfew things :
- sys.syslogins is deprecated.
- dbatools has cmdlets for Login and user management which you can leverage for automation.
Code Snippets
USE [xxxx-xxxx]
create user [xxxx] from login [xxxx] <--- this is needed !
ALTER USER [xxxx] WITH DEFAULT_SCHEMA=[db_datareader]
ALTER ROLE [db_datareader] ADD MEMBER [xxxx]
ALTER ROLE [db_datawriter] ADD MEMBER [xxxx]
ALTER ROLE [db_owner] ADD MEMBER [xxxx]
GOContext
StackExchange Database Administrators Q#250143, answer score: 2
Revisions (0)
No revisions yet.