Create Login and Add User with SMO


  • Below works great to add login to SQL Server 2005 but I cannot figure out how to add user to database in SMO.  Any help would be greatly apprecitated.

    cn As New ServerConnection

    cn.LoginSecure = False

    cn.Login = gLogin

    cn.Password = gPassword

    cn.ServerInstance = gServer


    Dim srv As Server

    srv = New Server(cn)

    Dim lg As Login

    lg = New Login(srv, strLogin)

    lg.DefaultDatabase = strDefDB

    lg.LoginType = LoginType.SqlLogin


    Monday, November 14, 2005 2:57 PM

All replies

  • If someone could finish this old thread it would be much appreciated :)   I have the same problem
    Wednesday, February 25, 2009 6:05 PM
  • Here is how you create a login and a user that is associated/mapped to that login.

    In VB.NET (converted with a translation tool)
     server As
    Dim loginName As String = "MyNewLogin"
    Dim userName As String = "MyUserName"

    Dim login As New Login(server, loginName)
    login.LoginType = LoginType.SqlLogin
    login.Create("password" )

    Dim user As New User(server.Databases("dbName" ), userName)
    user.Login = login.Name
    In C#

    Server server = new Server();
    string loginName = "MyNewLogin";
    string userName = "MyUserName";
    Login login = new Login(server, loginName);
    login.LoginType = LoginType.SqlLogin;

    User user = new User(server.Databases["dbName"], userName);
    user.Login = login.Name;

    • Proposed as answer by Michael Dent Friday, July 06, 2012 8:17 AM
    Thursday, April 16, 2009 7:33 AM
  • Hi SpicyMikey,

    Martin Xie has created a walkthrough on how to create a multi-users management program which the administrator can add and delete user accounts.
    Thank you, msdn =) 99.9% of my questions have been answered :D
    Thursday, April 16, 2009 8:56 AM