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!
Edit
While I could use the execution plan suggested by Rob, I'd appreciate any alternative simple approaches.
Answering questions by tomekszpakowicz
Are you (or your application) source of the query in question? In that case you should know the aliases.
I am not the author of queries. We have a system where users can enter the query. We build columns out of it using the method I explained above. These details will be persisted and another user can use this like adding new criteria etc. So we need to build the SQL dynamically from the information we have. So when a column is aliased and we are not getting alias name, then the where clause constructed will be invalid.
Thanks