具有相同名称的SqlDataReader GetOrdinal

时间:2014-09-02 14:55:59

标签: c# sqldatareader

需要使用GetOrdinal中的SqlDataReader,但我的查询是连接并且多次包含相同的字段名称。 所以我试试

SELECT a.Id, b.Id FROM table1 AS a ...

但GetOrdinal似乎不是t understand the schema alias... GetOrdinal(' a.Id') 抛出异常......无论如何都存档这个?

2 个答案:

答案 0 :(得分:6)

在查询中提供别名

SELECT a.Id As EmployeeID, b.Id as ManagerId FROM table1 AS a ..

现在,您可以在代码中使用别名来读取值

var employeeIdIndex = reader.GetOrdinal("EmployeeID")

答案 1 :(得分:3)

我自己也有同样的问题,我发现两个常见的答案是:

  • 别名SQL
  • 中的字段
  • 使用列
  • 的整数索引

我不喜欢这两个选项,所以我创建了第三个:GetNthOrdinal。

using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;

public static class SqlDataReaderExtensions
{
    public static int GetNthOrdinal(this SqlDataReader reader, string columnName, int nthOccurrence = 1)
    {
        // Get the schema which represents the columns in the reader
        DataTable schema = reader.GetSchemaTable();

        // Find all columns in the schema which match the name we're looking for.
        // schema is a table and each row is a column from our reader.
        var occurrences = schema.Rows.Cast<DataRow>().Where(r => string.Equals((string)r["ColumnName"], columnName, StringComparison.Ordinal));

        // Get the nthOccurrence.  Will throw if occurrences is empty.
        // reader.GetOrdinal will also throw if a column is not present, but you may want to
        // have this throw a more meaningful exception
        var occurrence = occurrences.Skip(nthOccurrence - 1).First();

        // return the ordinal
        return (int)occurrence["ColumnOrdinal"];
    }
}

用法:

reader.GetNthOrdinal("Id", 2);

重要的是要注意第n次出现不是基于0的;它从1开始。