Compartir a través de


How to: Enumerate Logins and Associated Users in Visual Basic .NET

This section describes how to enumerate a list of logons and their associated users by using Microsoft Visual Basic .NET.

Every user in a database is associated with a logon. The logon can be associated with users in more than one database. The code example shows how to call the EnumDatabaseMappings method of the Login object to list all the database users who are associated with the logon. The example creates a logon and user in the AdventureWorks database to make sure there is mapping information to enumerate.

Enumerating logons and users

  1. Start Visual Studio 2005.

  2. From the File menu, select New Project. The New Project dialog box appears.

  3. In the Project Types pane, select Visual Basic. In the Templates pane, select Console Application.

  4. (Optional) In the Name box, type the name of the new application.

  5. Click OK to load the Visual Basic console application template.

  6. On the Project menu, select Add Reference item. The Add Reference dialog box appears. Select Browse and locate the SMO assemblies in the C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies folder. Select the following files:

    Microsoft.SqlServer.ConnectionInfo.dll

    Microsoft.SqlServer.Smo.dll

    Microsoft.SqlServer.SqlEnum.dll

    Microsoft.SqlServer.SmoEnum.dll

  7. On the View menu, click Code.-Or-Select the Module1.vb window to display the code window.

  8. In the code, before any declarations, type the following Imports statements to qualify the types in the SMO namespace:

    Imports Microsoft.SqlServer.Management.Smo
    Imports Microsoft.SqlServer.Management.Common
    
  9. Insert the code that follows this procedure into the main program.

  10. Run and build the application.

Ejemplo

'Connect to the local, default instance of SQL Server.
Dim srv As Server
srv = New Server
'Iterate through each database and display.
Dim db As Database
For Each db In srv.Databases
    Console.WriteLine("============================================")
    Console.WriteLine("Login Mappings for the database: " + db.Name)
    Console.WriteLine(" ")
    'Run the EnumLoginMappings method and return details of database user-login mappings to a DataTable object variable.
    Dim d As DataTable
    d = db.EnumLoginMappings
    'Display the mapping information.
    Dim r As DataRow
    Dim c As DataColumn
    For Each r In d.Rows
        For Each c In r.Table.Columns
            Console.WriteLine(c.ColumnName + " = " + r(c))
        Next
        Console.WriteLine(" ")
    Next
Next

Vea también

Conceptos

Managing Users, Roles, and Logins

Ayuda e información

Obtener ayuda sobre SQL Server 2005