views:

55

answers:

4

I have an SQL query I get from a configuration file, this query usually contains 3-6 joins.

I need to find at run time, based on the result set represented by SqlDataReader, to find the name of the table for each column.

Here are some thing that don't work:

  • SqlDataReader.GetName returns the column name but not the table name.
  • SqlDataReader.GetSchemaTable returns a data table with column information - but all the table names are null.
  • Querying information_schema doesn't help because I need data on the results of the current query (and the column names are not unique - there are columns with the same name in different tables).

I'm using .net 3.5SP1/ C#/ SQL Server 2008 in a console application.

EDIT: I know this is not possible for all cases since a "column" can be combined from multiple tables, a function or even a constant expression - I'm looking for something that works in the simple case.

EDIT 2: Found out why it didn't work - You can use SqlDataReader.GetSchemaTable to get table information but you have to set CommandBehavior to KeyInfo, you do that in the ExecuteReader call:

reader = cmd.ExecuteReader(CommandBehavior.KeyInfo);
+1  A: 

I don't know if this information is available. In particular, not all columns of a result set come from a table. From a relational point of view, tables and resultsets are the same thing.

John Saunders
A: 

This unanswered question on stackoverflow uses SqlDataReader.GetSchemaTable to get the table name. Their problem is that it returns the actual table name rather than the alias that the table has. Not sure if this works with your sql but figured I'd let you know just in case.

Kyra
A: 

You can use SqlDataReader.GetSchemaTable to get table information but you have to set CommandBehavior to KeyInfo, you do that in the ExecuteReader call:

reader = cmd.ExecuteReader(CommandBehavior.KeyInfo);
Nir
+1  A: 

In general, this is not possible. Consider the following query:

SELECT col1 FROM table1
UNION ALL
SELECT col1 FROM table2

Clearly col1 comes from more than one table.

AlexKuznetsov