Getting table schema from a query
Posted
by Appu
on Stack Overflow
See other posts from Stack Overflow
or by Appu
Published on 2010-06-17T05:36:19Z
Indexed on
2010/06/17
5:43 UTC
Read the original article
Hit count: 298
As per MSDN, SqlDataReader.GetSchemaTable
returns column metadata for the query executed. I am wondering is there a similar method that will give table metadata for the given query? I mean what tables are involved and what aliases it has got.
In my application, I get the query and I need to append the where
clause programically. Using GetSchemaTable()
, I can get the column metadata and the table it belongs to. But even though table has aliases, it still return the real table name. Is there a way to get the aliase name for that table?
Following code shows getting the column metadata.
const string connectionString = "your_connection_string";
string sql = "select c.id as s,c.firstname from contact as c";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand command = new SqlCommand(sql, connection))
{
connection.Open();
SqlDataReader reader = command.ExecuteReader(CommandBehavior.KeyInfo);
DataTable schema = reader.GetSchemaTable();
foreach (DataRow row in schema.Rows)
{
foreach (DataColumn column in schema.Columns)
{
Console.WriteLine(column.ColumnName + " = " + row[column]);
}
Console.WriteLine("----------------------------------------");
}
Console.Read();
}
This will give me details of columns correctly. But when I see BaseTableName
for column Id
, it is giving contact
rather than the alias name c
. Is there any way to get the table schema and aliases from a query like the above?
Any help would be great!
© Stack Overflow or respective owner