Thursday, March 29, 2012

Field Names from SQL Statement

Is there anyway to determine what the resulting Field Names are going to be from a SQL Statement?

For example:
SELECT TABLE1.FIELD1, TABLE1.FIELD2, TABLE1.FIELD3, TABLE2.FIELD1 AS ANOTHERNAME
FROM TABLE1 INNER JOIN TABLE2 ON TABLE1.PK = TABLE2.FK

resulting field names:
FIELD1
FIELD2
FIELD3
ANOTHERNAME

Seems easy enough splitting all values before "FROM" by comma and doing some manipulation to remove table names and anything before the word "AS". However, it gets more difficult when you have complex CASE statements embedded in you query that may also contain commas.

Just a shot in the dark because I don't know if anyone has already done something like this before.

Thank you in advance,

JeffI'm not quite sure what you are after... but, assuming that all columns are aliased... it would be the 'word' preceding the commas and the FROM.

Where are you trying to consume this from? ADO.NET will expose these field names to you, or are you looking to somehow consume them in just SQL Server?

--Mike|||What I am trying to do is build a report editor whereby the user simply enters a SQL statement on one tab. The second tab would then contain a datagrid with the field names as one column and some other columns that are formatting the report such as column width, forecolor, etc. for each field. All of this information is then written to a database table to be used later to restore that report definitions which are used to build a dynamic datagrid to display the results of the query.

Unfortunately, not all fields are aliased so I cannot simply use those words that precede a comma. Additionally, there are also times when fields are concatenated and include commas such as TABLE1.LAST_NAME + ', ' + TABLE1.FIRST_NAME AS FULL_NAME.

No comments:

Post a Comment