使用集合
集合是指从相同对象类构造的并共享同一父对象的对象列表。 集合对象始终包含对象类型的名称并具有 Collection 后缀。 例如,若要访问指定表中的列,请使用 ColumnCollection 对象类型。 它包含所有属于同一 Column 对象的 Table 对象。
Microsoft Visual Basic For...Each
语句或 Microsoft Visual 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 中使用集合来引用对象
此代码示例演示如何使用 Columns、Tables 和 Databases 属性来设置列属性。 这些属性表示集合,当这些属性与指定对象名称的参数一起使用时可用来标识特定对象。 Tables 集合对象属性需要名称和架构。
在 Visual C# 中使用集合来引用对象
此代码示例演示如何使用 Columns、Tables 和 Databases 属性来设置列属性。 这些属性表示集合,当这些属性与指定对象名称的参数一起使用时可用来标识特定对象。 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("AdventureWorks2012").Tables("Person", "Person").Columns("LastName").Nullable = true;
//Call the Alter method to make the change on the instance of SQL Server.
srv.Databases("AdventureWorks2012").Tables("Person", "Person").Columns("LastName").Alter();
}
在 Visual Basic 中遍历集合中的成员
此代码示例循环访问Databases集合属性,并显示SQL Server实例的所有数据库连接。
在 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);
}