0

I have a simple routine that takes a SELECT statement and uses a DataTable.

I use the same SELECT statement and pass it through a routine to generate an array of column names and data types.

As long as the SELECT statement is simple

e.g SELECT Firstname,Secondname...etc...

... my routine can add the column information to my array

However, if the SELECT statement is a little more complex

e.g. SELECT Firstname,Secondname AS Surname... etc...

... my routine will fall over because Surname is not a column name.

More complexity can occur when you factor in subqueries and aggregate columns.

I am looking for a more elegant approach if there is one to acquire any base column names from a SELECT statement?

3
  • Where does the 'routine' get the column names from? Are you using a dataadaptor to populate the datatable, in which case the columns should be fine? Commented Oct 17, 2013 at 13:34
  • As long as your DB is simple and efficient designed you can find an elegant query. If your "names" table is complicated and complex every query will have troubles getting the results.. Commented Oct 17, 2013 at 13:35
  • So, you are asking how to parse an SQL Statment into a schema? Commented Oct 17, 2013 at 13:42

2 Answers 2

2

You have a DataTable.Columns property were every object is a DataColumn, which is populated based on the query you made.

So if you used as inside your SQL syntax, you should find the same name inside that collection too.

Sign up to request clarification or add additional context in comments.

3 Comments

Using my original example, "Surname" would get returned from the DataColumn, not Secondname, which is not what I need
@user2890085: don't think you can achieve this, as this is SQL syntax that generates data back to DataTable. Not very sure if there is any other property that refers to column real name, as from data perspective the real name is actually that one declared in "as" clause.
@user2890085: you can always execute another query that asks for real column names, but this sound kind of overkill..
0

You can use an ExecuteReader to execute the query. Then you can use GetName() to obtain the name of each field coming back.

2 Comments

Thanks for that. I should have mentioned that this is a MsAccess table, but the GetName() method will be useful if/when we port to MSSQL.
It is a member of DbDataReader, so it is DB independent actually. I update the response to reflect that, more correct in any case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.