Problem creating user in SqlServer using smo

1) If the username 'user1' already exists, then I create user 'user1' for the database 'db1' by calling the CreateDatabaseUser function

2) Otherwise, I create a login 'user1' with the password 'password1' with the default database as 'db1' (only after creating db1) using CreateServerLogin , and then create user 'user1' for 'db1' using CreateDatabaseUser

Method (2) throws an exception in newUser.Create(); in CreateDatabaseUser

saying Microsoft.SqlServer.Management.Smo.FailedOperationException: Create failed for User 'user1'. ---> Microsoft.SqlServer.Management.Common.ExecutionFailureException: An exception occurred while executing a Transact-SQL statement or batch. --- > System.Data.SqlClient.SqlException: '[user1]' is not a valid login or you do not have permission. Microsoft.SqlServer.Management.Smo.FailedOperationException: Create failed for User 'user1'. ---> Microsoft.SqlServer.Management.Common.ExecutionFailureException: An exception occurred while executing a Transact-SQL statement or batch. --- > System.Data.SqlClient.SqlException: '[user1]' is not a valid login or you do not have permission.

What could be the problem?

 private static Login CreateServerLogin(Server server, string database, string login, string password) { var newLogin = new Login(server, login) { LoginType = LoginType.SqlLogin, DefaultDatabase = database, PasswordPolicyEnforced = false }; newLogin.Create(password); return newLogin; } private static User CreateDatabaseUser(Database database, string user, string login) { var newUser = new User(database, user) { UserType = UserType.SqlLogin, Login = login }; newUser.Create(); newUser.AddToRole("db_owner"); return newUser; } 
+4
source share
1 answer

check transactions and parties.

DDL operators also support transactions, so when you create a login to enter a new user and password, there may not be such a login on the server, since the previous statement was not committed.

Also the batch closure operator "GO" will help


Try it first:

  • CreateServerLogin

  • issuing GO

  • Createdblogin

  • issue COMMIT


if failed to execute this logic:

  • CreateServerLogin

  • issue COMMIT

  • Createdblogin

0
source

All Articles