问题描述
我有一个SQL查询我从配置文件中得到,该查询通常包含3-6个连接。
我需要找到在运行时,基于SqlDataReader的psented,查找表中每一列的名称,结果集重$ P $。
下面是一些事情,不工作:
- SqlDataReader.GetName返回列名而不是表名。
- SqlDataReader.GetSchemaTable返回其列信息的数据表 - 但所有的表名是空 。
- 查询INFORMATION_SCHEMA没有帮助,因为我需要对当前查询的结果数据(和列名不是唯一的 - 有列在不同的表相同的名称)。
我使用一个控制台应用程序。NET 3.5SP1 / C#/ SQL Server 2008中。
编辑:我知道这是不可能适用于所有情况,因为一个列可以从多个表,函数,甚至一个恒定的前pression结合起来 - 我在寻找一些在简单情况下工作。
编辑2:找到了原因没有奏效 - 您可以使用SqlDataReader.GetSchemaTable获取表信息,但你必须设置的CommandBehavior为密钥信息,你这样做了的ExecuteReader电话:
读卡器= cmd.ExecuteReader(CommandBehavior.KeyInfo);
您可以使用SqlDataReader.GetSchemaTable获取表信息,但你必须设置的CommandBehavior为密钥信息,你这样做了的ExecuteReader电话:
读卡器= cmd.ExecuteReader(CommandBehavior.KeyInfo);
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);
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);
这篇关于如何从SqlDataReader的列的表名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!