2014-09-02 2 views
4

SqlDataReader에서 GetOrdinal을 사용해야하지만 내 쿼리는 조인을 사용하며 동일한 필드 이름을 여러 번 포함합니다. 이 아카이브 어쨌든 ... 거기 그래서 나는동일한 이름을 가진 SqlDataReader GetOrdinal

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

하려고하지만 GetOrdinal은 돈 t understand the schema alias... GetOrdinal ('a.Id')가` 는 예외를 throw 보인다?

+0

왜 이름이 필요합니까? 당신은'reader.GetInt32 (0)'과'reader.GetInt32 (1)'을 사용할 수 있습니다. –

답변

5

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

지금 내가이 같은 질문을했다

var employeeIdIndex = reader.GetOrdinal("EmployeeID") 
+0

그게 내가 피하려고하는 이유입니다. – Sebastian

+2

왜 그걸 피하기를 원합니까? – Shyju

+2

피할 수있는 방법이 없습니다. 이름은 고유해야합니다. – TomTom

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 시부 터 시작합니다.

+1

몇 년 후이 앨리 앨리어싱이 나를위한 옵션이 아니라는 주된 이유는 SQL을 수정할 수있는 능력이 없다는 것입니다. SQL 쿼리를 수정할 수있는 기능이 있으면 앨리어싱이 가장 좋은 옵션입니다. – dshapiro

관련 문제