I’m using the following to create a user if it doesn’t already exist in the database:
use DBExample
GO
IF NOT EXISTS (SELECT * from sys.database_role_members WHERE USER_NAME(member_principal_id) = 'user1')
BEGIN
CREATE USER [user1] WITH PASSWORD = 'abc')
END
EXEC sp_addrolemember 'role1', 'user1'
GO
DBExample already has a user1, so when I try to run the script, SQL Server Management Studio complains about an ‘Incorrect syntax near ‘user1’. (in the create user line)
What am I missing to make this work?
I used the answer found here: https://stackoverflow.com/a/6159882 to make use of variables to substitute the user name to get around the ‘There is already login/user named xxx in the database’ error SSMS was complaining about. The code looks like this at the end: