1) 如果已经有一个登录名“user1”,那么我通过调用
CreateDatabaseUser
作用
2) 否则,我将创建一个登录名“user1”,密码为“password1”,默认数据库为“db1”(仅在创建db1之后),使用
CreateServerLogin
然后我使用
CreateDatabaseUser
方法(2)在
newUser.Create();
在里面
CreateDatabaseUser
说
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.
有什么问题吗?
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;
}