Share via


Llamar a métodos

Los métodos realizan tareas específicas relacionadas con el objeto, como la emisión de un Checkpoint en una base de datos o la solicitud de una lista enumerada de inicios de sesión para la instancia de Microsoft SQL Server.

Los métodos realizan una operación en un objeto. Los métodos pueden tomar parámetros y a menudo tener un valor devuelto. El valor devuelto puede ser un tipo de datos simple, un objeto complejo o una estructura que contiene muchos miembros.

Use el control de excepciones para detectar si el método se realizó correctamente. Para obtener más información, vea Controlar excepciones SMO.

Ejemplos

Para utilizar cualquier ejemplo de código que se proporcione, deberá elegir el entorno de programación, la plantilla de programación y el lenguaje de programación en los que crear su aplicación. Para obtener más información, vea "Cómo crear un proyecto de Visual Basic SMO en Visual Studio .NET" o "Cómo crear un proyecto de Visual C# SMO en Visual Studio .NET" en los Libros en pantalla de SQL Server.

Usar un método SMO simple en Visual Basic

En este ejemplo, el método Create no toma ningún parámetro y no devuelve ningún valor.

'Connect to the local, default instance of SQL Server.
Dim srv As Server
srv = New Server
'Define a Database object variable by supplying the parent server and the database name arguments in the constructor.
Dim db As Database
db = New Database(srv, "Test_SMO_Database")
'Call the Create method to create the database on the instance of SQL Server. 
db.Create()

Usar un método SMO simple en Visual C#

En este ejemplo, el método Create no toma ningún parámetro y no devuelve ningún valor.

{ 
//Connect to the local, default instance of SQL Server. 
Server srv; 
srv = new Server(); 
//Define a Database object variable by supplying the parent server and the database name arguments in the constructor. 
Database db; 
db = new Database(srv, "Test_SMO_Database"); 
//Call the Create method to create the database on the instance of SQL Server. 
db.Create(); 

}

Usar un método SMO con un parámetro en Visual Basic

El objeto Table tiene un método denominado RebuildIndexes. Este método requiere un parámetro numérico que especifica FillFactor.

Dim srv As Server
srv = New Server
Dim tb As Table
tb = srv.Databases("AdventureWorks2008R2").Tables("Employee", "HumanResources")
tb.RebuildIndexes(70)

Usar un método SMO con un parámetro en Visual C#

El objeto Table tiene un método denominado RebuildIndexes. Este método requiere un parámetro numérico que especifica FillFactor.

{ 
Server srv = default(Server); 
srv = new Server(); 
Table tb = default(Table); 
tb = srv.Databases("AdventureWorks2008R2").Tables("Employee", "HumanResources"); 
tb.RebuildIndexes(70); 
} 

Usar un método de enumeración que devuelve un objeto DataTable en Visual Basic

En esta sección se describe cómo llamar a un método de enumeración y cómo controlar los datos del objeto DataTable devuelto.

El método EnumCollations devuelve un objeto DataTable, que requiere más navegación para tener acceso a toda la información de intercalación disponible acerca de la instancia de SQL Server.

'Connect to the local, default instance of SQL Server.
Dim srv As Server
srv = New Server
'Call the EnumCollations method and return collation information to DataTable variable.
Dim d As DataTable
'Select the returned data into an array of DataRow.
d = srv.EnumCollations
'Iterate through the rows and display collation details for the instance of SQL Server.
Dim r As DataRow
Dim c As DataColumn
For Each r In d.Rows
    Console.WriteLine("============================================")
    For Each c In r.Table.Columns
        Console.WriteLine(c.ColumnName + " = " + r(c).ToString)
    Next
Next

Usar un método de enumeración que devuelve un objeto DataTable en Visual C#

En esta sección se describe cómo llamar a un método de enumeración y cómo controlar los datos del objeto DataTable devuelto.

El método EnumCollations devuelve un objeto DataTable del sistema. El objeto DataTable requiere más navegación para obtener acceso a toda la información de intercalación disponible acerca de la instancia de SQL Server.

//Connect to the local, default instance of SQL Server. 
{ 
Server srv = default(Server); 
srv = new Server(); 
//Call the EnumCollations method and return collation information to DataTable variable. 
DataTable d = default(DataTable); 
//Select the returned data into an array of DataRow. 
d = srv.EnumCollations; 
//Iterate through the rows and display collation details for the instance of SQL Server. 
DataRow r = default(DataRow); 
DataColumn c = default(DataColumn); 
foreach ( r in d.Rows) { 
  Console.WriteLine("====================================="); 
  foreach ( c in r.Table.Columns) { 
    Console.WriteLine(c.ColumnName + " = " + r(c).ToString); 
  } 
} 
} 

Construir un objeto en Visual Basic

Se puede llamar al constructor de cualquier objeto mediante el operador New. El constructor de objeto Database se sobrecarga y la versión del constructor de objeto Database que se usa en el ejemplo toma dos parámetros: el objeto primario Server al que pertenece la base de datos y una cadena que representa el nombre de la nueva base de datos.

'Connect to the local, default instance of SQL Server.
Dim srv As Server
srv = New Server
'Declare and define a Database object by supplying the parent server and the database name arguments in the constructor.
Dim d As Database
d = New Database(srv, "Test_SMO_Database")
'Create the database on the instance of SQL Server.
d.Create()
Console.WriteLine(d.Name)

Construir un objeto en Visual C#

Se puede llamar al constructor de cualquier objeto mediante el operador New. El constructor de objeto Database se sobrecarga y la versión del constructor de objeto Database que se usa en el ejemplo toma dos parámetros: el objeto primario Server al que pertenece la base de datos y una cadena que representa el nombre de la nueva base de datos.

{ 
Server srv; 
srv = new Server(); 
Table tb; 
tb = srv.Databases("AdventureWorks2008R2").Tables("Employee", "HumanResources"); 
tb.RebuildIndexes(70); 
//Connect to the local, default instance of SQL Server. 
Server srv; 
srv = new Server(); 
//Declare and define a Database object by supplying the parent server and the database name arguments in the constructor. 
Database d; 
d = new Database(srv, "Test_SMO_Database"); 
//Create the database on the instance of SQL Server. 
d.Create(); 
Console.WriteLine(d.Name); 
}

Copiar un objeto SMO en Visual Basic

En este ejemplo de código se usa el método Copy para crear una copia del objeto Server. El objeto Server representa una conexión a una instancia de SQL Server.

'Connect to the local, default instance of SQL Server.
Dim srv1 As Server
srv1 = New Server()
'Modify the default database and the timeout period for the connection.
srv1.ConnectionContext.DatabaseName = "AdventureWorks2008R2"
srv1.ConnectionContext.ConnectTimeout = 30
'Make a second connection using a copy of the ConnectionContext property and verify settings.
Dim srv2 As Server
srv2 = New Server(srv1.ConnectionContext.Copy)
Console.WriteLine(srv2.ConnectionContext.ConnectTimeout.ToString)

Copiar un objeto SMO en Visual C#

En este ejemplo de código se usa el método Copy para crear una copia del objeto Server. El objeto Server representa una conexión a una instancia de SQL Server.

{ 
//Connect to the local, default instance of SQL Server. 
Server srv1; 
srv1 = new Server(); 
//Modify the default database and the timeout period for the connection. 
srv1.ConnectionContext.DatabaseName = "AdventureWorks2008R2"; 
srv1.ConnectionContext.ConnectTimeout = 30; 
//Make a second connection using a copy of the ConnectionContext property and verify settings. 
Server srv2; 
srv2 = new Server(srv1.ConnectionContext.Copy); 
Console.WriteLine(srv2.ConnectionContext.ConnectTimeout.ToString); 
}

Supervisar los procesos de servidor en Visual Basic

Puede obtener la información de tipo de estado actual de la instancia de SQL Server a través de los métodos de enumeración. El ejemplo de código usa el método EnumProcesses para detectar información sobre los procesos actuales. También muestra cómo trabajar con las columnas y filas del objeto DataTable devuelto.

'Connect to the local, default instance of SQL Server.
Dim srv As Server
srv = New Server
'Call the EnumCollations method and return collation information to DataTable variable.
Dim d As DataTable
'Select the returned data into an array of DataRow.
d = srv.EnumProcesses
'Iterate through the rows and display collation details for the instance of SQL Server.
Dim r As DataRow
Dim c As DataColumn
For Each r In d.Rows
    Console.WriteLine("============================================")
    For Each c In r.Table.Columns
        Console.WriteLine(c.ColumnName + " = " + r(c).ToString)
    Next
Next

Supervisar los procesos de servidor en Visual C#

Puede obtener la información de tipo de estado actual de la instancia de SQL Server a través de los métodos de enumeración. El ejemplo de código usa el método EnumProcesses para detectar información sobre los procesos actuales. También muestra cómo trabajar con las columnas y filas del objeto DataTable devuelto.

//Connect to the local, default instance of SQL Server. 
{ 
Server srv = default(Server); 
srv = new Server(); 
//Call the EnumCollations method and return collation information to DataTable variable. 
DataTable d = default(DataTable); 
//Select the returned data into an array of DataRow. 
d = srv.EnumProcesses; 
//Iterate through the rows and display collation details for the instance of SQL Server. 
DataRow r = default(DataRow); 
DataColumn c = default(DataColumn); 
foreach ( r in d.Rows) { 
  Console.WriteLine("================================="); 
  foreach ( c in r.Table.Columns) { 
    Console.WriteLine(c.ColumnName + " = " + r(c).ToString); 
  } 
} 
} 

Vea también

Referencia