How to get table name of a column from SqlDataReader

时光总嘲笑我的痴心妄想 提交于 2019-12-03 13:09:13

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);

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.

Kyra

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.

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.

you can solve it like the following :

DataTable schemaTable = sqlReader.GetSchemaTable();

foreach (DataRow row in schemaTable.Rows)
{
    foreach (DataColumn column in schemaTable.Columns)
    {
        MessageBox.Show (string.Format("{0} = {1}", column.ColumnName, row[column]));
    }
}
reader = cmd.ExecuteReader();
reader.GetSchemaTable().Rows[0]["BaseTableName"];
Emre Kilinc Arslan
SqlCeConnection conn = new SqlCeConnection("Data Source = Database1.sdf");
SqlCeCommand query = conn.CreateCommand();
query.CommandText = "myTableName";
query.CommandType = CommandType.TableDirect;
conn.Open();
SqlCeDataReader myreader = query.ExecuteReader(CommandBehavior.KeyInfo);
DataTable myDataTable= myreader.GetSchemaTable();
//thats the code you asked. in the loop
for (int i = 0; i < myDataTable.Rows.Count; i++)
{
    listView1.Columns.Add(myDataTable.Rows[i][0].ToString());
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!