使用集合

集合是已經從相同物件類別建構,而且共用相同父物件的物件清單。集合物件一定會包含具有 Collection 後置詞之物件類型的名稱。例如,若要存取指定之資料表內的資料行,請使用 ColumnCollection 物件類型。它會包含屬於相同 Table 物件的所有 Column 物件。

Microsoft Visual Basic For...Each 陳述式或 Microsoft Visual C#foreach 陳述式可用來逐一查看集合的每一個成員。

範例

如果要使用所提供的任何程式碼範例,您必須選擇建立應用程式用的程式設計環境、程式設計範本,及程式設計語言。如需詳細資訊,請參閱《SQL Server 線上叢書》中的<如何:在 Visual Studio .NET 中建立 Visual Basic SMO 專案>或<如何:在 Visual Studio .NET 中建立 Visual C# SMO 專案>。

在 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("AdventureWorks2008R2").Tables("Person", "Person").Columns("ModifiedDate").Nullable = True
'Call the Alter method to make the change on the instance of SQL Server.
srv.Databases("AdventureWorks2008R2").Tables("Person", "Person").Columns("ModifiedDate").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("AdventureWorks2008R2").Tables("Person", "Person").Columns("LastName").Nullable = true; 
//Call the Alter method to make the change on the instance of SQL Server. 
srv.Databases("AdventureWorks2008R2").Tables("Person", "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); 
}