.NET Framework Class Library SqlDataReader..::.GetOrdinal Method Gets the column ordinal, given the name of the column.
Namespace:
System.Data.SqlClient
Assembly:
System.Data (in System.Data.dll)

Syntax

Exceptions

Remarks
GetOrdinal performs a case-sensitive lookup first. If it fails, a second, case-insensitive search occurs (a case-insensitive comparison is done using the database collation). Unexpected results can occur when comparisons are affected by culture-specific casing rules. For example, in Turkish, the following example yields the wrong results because the file system in Turkish does not use linguistic casing rules for the letter 'i' in "file". The method throws an IndexOutOfRange exception if the zero-based column ordinal is not found.
GetOrdinal is kana-width insensitive. Because ordinal-based lookups are more efficient than named lookups, it is inefficient to call GetOrdinal within a loop. Save time by calling GetOrdinal once and assigning the results to an integer variable for use within the loop.

Examples
The following example demonstrates how to use the GetOrdinal method.
Private Sub ReadGetOrdinal(ByVal connectionString As String)
Dim queryString As String = _
"SELECT DISTINCT CustomerID FROM dbo.Orders;"
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(queryString, connection)
connection.Open()
Dim reader As SqlDataReader = command.ExecuteReader()
' Call GetOrdinal and assign value to variable.
Dim customerID As Integer = reader.GetOrdinal("CustomerID")
' Use variable with GetString inside of loop.
While reader.Read()
Console.WriteLine("CustomerID={0}", reader.GetString(customerID))
End While
' Call Close when done reading.
reader.Close()
End Using
End Sub
private static void ReadGetOrdinal(string connectionString)
{
string queryString = "SELECT DISTINCT CustomerID FROM dbo.Orders;";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command =
new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// Call GetOrdinal and assign value to variable.
int customerID = reader.GetOrdinal("CustomerID");
// Use variable with GetString inside of loop.
while (reader.Read())
{
Console.WriteLine("CustomerID={0}", reader.GetString(customerID));
}
// Call Close when done reading.
reader.Close();
}
}

Version Information
.NET FrameworkSupported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0 .NET Framework Client ProfileSupported in: 4, 3.5 SP1

Platforms
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

See Also
|
Biblioteca de clases de .NET Framework SqlDataReader..::.GetOrdinal (Método) Obtiene el ordinal de la columna a partir del nombre de la columna determinado.
Espacio de nombres:
System.Data.SqlClient
Ensamblado:
System.Data (en System.Data.dll)

Sintaxis

Excepciones

Comentarios
GetOrdinal realiza primero una búsqueda en la que se distingue entre mayúsculas y minúsculas. Si se produce un error, se hace una segunda búsqueda sin distinción entre mayúsculas y minúsculas (la comparación sin distinción entre mayúsculas y minúsculas se lleva a cabo utilizando la intercalación de bases de datos). Si las operaciones de comparación se ven afectadas por las reglas de mayúsculas y minúsculas específicas de la referencia cultural actual, pueden obtenerse resultados inesperados. En el siguiente ejemplo, en turco, se generan resultados no válidos porque el sistema de archivos turco no utiliza las reglas lingüísticas de mayúsculas y minúsculas para la letra "i" de "file". El método inicia una excepción IndexOutOfRange si no se encuentra el ordinal de columna de base cero.
GetOrdinal no distingue el ancho kana. Como las búsquedas basadas en ordinales son más eficaces que las de nombres, es inútil llamar a GetOrdinal en un bucle. Ahorre tiempo llamando a GetOrdinal una vez y asignando los resultados a una variable de entero para utilizarla en el bucle.

Ejemplos
En el siguiente ejemplo se muestra cómo utilizar el método GetOrdinal.
Private Sub ReadGetOrdinal(ByVal connectionString As String)
Dim queryString As String = _
"SELECT DISTINCT CustomerID FROM dbo.Orders;"
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(queryString, connection)
connection.Open()
Dim reader As SqlDataReader = command.ExecuteReader()
' Call GetOrdinal and assign value to variable.
Dim customerID As Integer = reader.GetOrdinal("CustomerID")
' Use variable with GetString inside of loop.
While reader.Read()
Console.WriteLine("CustomerID={0}", reader.GetString(customerID))
End While
' Call Close when done reading.
reader.Close()
End Using
End Sub
private static void ReadGetOrdinal(string connectionString)
{
string queryString = "SELECT DISTINCT CustomerID FROM dbo.Orders;";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command =
new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// Call GetOrdinal and assign value to variable.
int customerID = reader.GetOrdinal("CustomerID");
// Use variable with GetString inside of loop.
while (reader.Read())
{
Console.WriteLine("CustomerID={0}", reader.GetString(customerID));
}
// Call Close when done reading.
reader.Close();
}
}

Información de versión
.NET FrameworkCompatible con: 4, 3.5, 3.0, 2.0, 1.1, 1.0 .NET Framework Client ProfileCompatible con: 4, 3.5 SP1

Plataformas
Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2
.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

Vea también
|