使用集合

集合是指从相同对象类构造的并共享同一父对象的对象列表。集合对象始终包含对象类型的名称并具有 Collection 后缀。例如,若要访问指定表中的列,请使用 ColumnCollection 对象类型。它包含所有属于同一 Table 对象的 Column 对象。

MicrosoftVisual BasicFor...Each 语句或 MicrosoftVisual C#foreach 语句可用于遍历集合的每个成员。

示例

若要使用所提供的任何代码示例,您必须选择创建应用程序所需的编程环境、编程模板和编程语言。 有关详细信息,请参阅 SQL Server 联机丛书中的“How to: Create a Visual Basic SMO Project in Visual Studio .NET”或“How to: Create a Visual C# SMO Project in Visual Studio .NET”。

在 Visual Basic 中使用集合来引用对象

此代码示例演示如何使用 ColumnsTablesDatabases 属性来设置列属性。这些属性表示集合,当这些属性与指定对象名称的参数一起使用时可用来标识特定对象。Tables 集合对象属性需要名称和架构。

'Connect to the local, default instance of SQL Server.
Dim srv As Server
srv = New Server
'Modify a property using the Databases, Tables, and Columns collections to reference a column.
srv.Databases("AdventureWorks").Tables("Contact", "Person").Columns("LastName").Nullable = True
'Call the Alter method to make the change on the instance of SQL Server.
srv.Databases("AdventureWorks").Tables("Contact", "Person").Columns("LastName").Alter()

在 Visual C# 中使用集合来引用对象

此代码示例演示如何使用 ColumnsTablesDatabases 属性来设置列属性。这些属性表示集合,当这些属性与指定对象名称的参数一起使用时可用来标识特定对象。Tables 集合对象属性需要名称和架构。

{ 
//Connect to the local, default instance of SQL Server. 
Server srv; 
srv = new Server(); 
//Modify a property using the Databases, Tables, and Columns collections to reference a column. 
srv.Databases("AdventureWorks").Tables("Contact", "Person").Columns("LastName").Nullable = true; 
//Call the Alter method to make the change on the instance of SQL Server. 
srv.Databases("AdventureWorks").Tables("Contact", "Person").Columns("LastName").Alter(); 
}

在 Visual Basic 中遍历集合中的成员

此代码示例可遍历 Databases 集合属性并显示数据库与 SQL Server 实例之间的所有连接。

'Connect to the local, default instance of SQL Server.
Dim srv As Server
srv = New Server
Dim count As Integer
Dim total As Integer
'Iterate through the databases and call the GetActiveDBConnectionCount method.
Dim db As Database
For Each db In srv.Databases
    count = srv.GetActiveDBConnectionCount(db.Name)
    total = total + count
    'Display the number of connections for each database.
    Console.WriteLine(count & " connections on " & db.Name)
Next
'Display the total number of connections on the instance of SQL Server.
Console.WriteLine("Total connections =" & total)

在 Visual C# 中遍历集合中的成员

此代码示例可遍历 Databases 集合属性并显示数据库与 SQL Server 实例之间的所有连接。

//Connect to the local, default instance of SQL Server. 
{ 
Server srv = default(Server); 
srv = new Server(); 
int count = 0; 
int total = 0; 
//Iterate through the databases and call the GetActiveDBConnectionCount method. 
Database db = default(Database); 
foreach ( db in srv.Databases) { 
  count = srv.GetActiveDBConnectionCount(db.Name); 
  total = total + count; 
  //Display the number of connections for each database. 
  Console.WriteLine(count + " connections on " + db.Name); 
} 
//Display the total number of connections on the instance of SQL Server. 
Console.WriteLine("Total connections =" + total); 
}