tags:

views:

242

answers:

1

I have a sql select like so which returns a datatable:

select * from table1 a join table2 b on a.id=b.id

Both table1 and table2 have a column named itemno .

How do i reference the 2 separate columns? Normally I would use something like:

datarow["itemno"].ToString(); <=first column named itemno only
datarow["b.itemno"].ToString(); <= fail

However this only seems to get the first column named itemno.
Is there a way to reference the second column named itemno without changing my sql statement? (I know i can change my sql statement, take out the * and put in column aliases).

+2  A: 

You can reference the columns by index instead:

datarow[0].ToString();

I'd much prefer aliasing them though to be honest.

AdaTheDev
You are right, and that is the only alternative.
Max
Here is the danger hidden. If you change you query later a little and it will start to return the columns in a different order, you code will stop working.
Developer Art
Good point NewInTown. The aliasing is by far the best way to do it.
Max
Alias them in the SQL statement? It's a very long sql statment with lots of columns. I guess that's my only choice as I'd rather not use a numerical index.I can't believe there is no way to reference columns with the same name in ADO/C#.
muhan
Yes. It's generally a good idea to list the specific columns to return anyway to prevent returning unneccessary data and can result in better query performance. So would be a good idea to think about whether you need all columns returned anyway.
AdaTheDev