ikantspelwurdz
Well-known member
- Joined
- Dec 8, 2009
- Messages
- 49
- Programming Experience
- 1-3
Suppose a database with two tables, "Main" and "Users."
Main:
Users:
I've got a SQL statement that looks something like this:
select User1.Name, User2.Name from main
inner join Users as User1 on main.User1ID = User1.UserID
inner join Users as User2 on main.User2ID = User2.UserID
The SQL itself works fine. But I want to read this data using a SQLDataReader, and I want to reference by column name, not column index.
This code:
...does not work. It crashes with IndexOutOfRangeException. These columns do not exist. A look at the metadata shows both columns are called "Name."
This code:
...runs, but both strings are going to be "Alice."
How can I best solve this problem? Going by column index isn't a good solution; the indices could (and almost certainly will) change. Using multiple SQLDataReaders would work, but I'd prefer a more elegant solution if there is one.
Main:
ID | User1ID | User2ID |
1 | 1 | 2 |
Users:
UserID | Name |
1 | Alice |
2 | Bob |
I've got a SQL statement that looks something like this:
select User1.Name, User2.Name from main
inner join Users as User1 on main.User1ID = User1.UserID
inner join Users as User2 on main.User2ID = User2.UserID
The SQL itself works fine. But I want to read this data using a SQLDataReader, and I want to reference by column name, not column index.
This code:
VB.NET:
Dim reader As SqlDataReader = ExecuteReader(sql)
reader.Read()
Dim alice as String = reader.Item("User1.Name")
Dim bob as String = reader.Item("User2.Name")
...does not work. It crashes with IndexOutOfRangeException. These columns do not exist. A look at the metadata shows both columns are called "Name."
This code:
VB.NET:
Dim reader As SqlDataReader = ExecuteReader(sql)
reader.Read()
Dim alice as String = reader.Item("Name")
Dim bob as String = reader.Item("Name")
...runs, but both strings are going to be "Alice."
How can I best solve this problem? Going by column index isn't a good solution; the indices could (and almost certainly will) change. Using multiple SQLDataReaders would work, but I'd prefer a more elegant solution if there is one.