如何使用 SELECT * 访问 SQL 查询中的不明确列
当我执行存储过程时,
SELECT * FROM Users
INNER JOIN BloodBankUser ON Users.UserID = BloodBankUser.UserID
它给出的结果很好。
但现在在 .net 方面,
dt.Rows[0]["Address"].ToString();
这给了我表 BloodBankUser 的地址,
dt.Rows[0]["Users.Address"].ToString();
当我调试此语句时,它执行错误
列“Users.Address”不 属于表。
如何获取 Users.Address 的值
When I execute Stored Procedure
SELECT * FROM Users
INNER JOIN BloodBankUser ON Users.UserID = BloodBankUser.UserID
It gives me result fine.
but now on .net side
dt.Rows[0]["Address"].ToString();
this gives me Address of table BloodBankUser
dt.Rows[0]["Users.Address"].ToString();
when I debug this statement it execute error
Column 'Users.Address' does not
belong to table.
How can I get Value of Users.Address
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
虽然第一个答案是更改 SQL 查询,为每个字段指定不同的名称,但仍然可以检索与您的字段关联的表名称。
在此示例中,我没有使用
DataAdapter
填充DataTable
,而是使用SqlDataReader
。请注意,如果您因任何原因无法检索数据库架构,这可能会失败
在
SqlCommand
上调用ExecuteReader
时,会出现过载它允许您指定CommandBehavior。在我们的例子中,我们想要的行为是CommandBehavior.KeyInfo。现在,在阅读器上,您可以调用
GetSchemaTable
方法。它返回一个包含查询结构的DataTable
。您可以在 MSDN 上了解该表。
我们现在的目标是将字段和表与其在列列表中的顺序位置进行匹配。架构表中的三个字段与您的兴趣相关:
然后您可以创建一个扩展方法来执行该读取:
然后您可以调用该扩展方法
While the first answer would be to change your SQL Query to specify a distinct name for each of your field, it is still possible to retrieve the table name associated with your field.
In this example, I am not filling a
DataTable
using aDataAdapter
, but rather I am using theSqlDataReader
.Be aware that this may fail if you are unable to retrieve the database schema for any reason
When calling
ExecuteReader
on aSqlCommand
, there is an overload that allows you to specify aCommandBehavior
. In our case, the behavior that we want isCommandBehavior.KeyInfo
.Now, on the reader, you can invoke the
GetSchemaTable
method. It returns aDataTable
that contains the structure of your query.You can read about that table on MSDN.
Our goal now is to match the field and table against its ordinal position in the column list. Three fields from the schema table are relevant to your interest:
You can then create an extension method to do that reading:
You can then call that extension method
重命名输出中的字段(选择FIELDNAME为NEWNAME)
Rename the FIELD in the output (Select FIELDNAME as NEWNAME)
您指定列名而不是使用 SELECT * FROM 然后您将能够执行以下操作
You specify the column names rather than use
SELECT * FROM
You will then be able to do the following避免在
SELECT
查询中使用*
。仅选择您需要的列并明确命名它们以避免歧义,Avoid the use of
*
inSELECT
queries. Select only the columns you need and name them explicitly to avoid ambiguity,代替
SELECT *...
明确指定您想要的列,并为可能重复的列添加别名Insead of
SELECT *...
specify the columns you want explicitly, and alias those that may duplicate