【问题标题】:SqlDataReader GetOrdinal with same nameSqlDataReader GetOrdinal 同名
【发布时间】:2014-09-02 14:55:58
【问题描述】:

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

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

但 GetOrdinal 似乎 dont understand the schema alias...GetOrdinal('a.Id')` 抛出异常...无论如何要存档吗?

【问题讨论】:

  • 你为什么需要这个名字?你可以使用reader.GetInt32(0)reader.GetInt32(1)

标签: c# sqldatareader


【解决方案1】:

在查询中提供别名

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

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

var employeeIdIndex = reader.GetOrdinal("EmployeeID")

【讨论】:

  • 这是我尽量避免的:)
  • 为什么要避免这种情况?
  • 但是有了模式别名,它在某种程度上是独一无二的,所以需要做更多的工作
  • @Sebastian 我认为您试图以错误的方式解决问题。你想达到什么目的?
  • 我有一个类似于我描述的方式的语句,在应用程序中我知道架构别名和字段名称,所以我需要列的索引来获取数据。但这似乎是不可能的
【解决方案2】:

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

  • 为 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 开始。

【讨论】:

  • 几年后回到这个话题,我想说,别名对我来说不是一个选项的主要原因是我没有能力修改 SQL。鉴于能够修改 SQL 查询,别名是最好的选择。
猜你喜欢
  • 2010-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多