Problem in creating User in SqlServer using smo

删除回忆录丶 提交于 2019-12-07 11:19:48

问题


1) If there is already a login 'user1' then I create a user 'user1' for database 'db1' by calling CreateDatabaseUser function

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

Method (2) throws an exception at 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.

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;
}


回答1:


check up transactions and batches.

DDL statements also support transactions, so when you create new user and pass server login, there might not be such login on the server because previous statement being not committed.

Also batch close statement "GO" would help


Try first:

  • CreateServerLogin

  • issue GO

  • CreateDBLogin

  • issue COMMIT


if failed try this logic:

  • CreateServerLogin

  • issue COMMIT

  • CreateDBLogin



来源:https://stackoverflow.com/questions/3520589/problem-in-creating-user-in-sqlserver-using-smo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!