我以前从未使用过涉及多个表的选择查询,现在当我这样做时,我遇到了从中获取信息的麻烦DataTable
.
我有这个问题:
SELECT * FROM [Usergroups], [Groups] WHERE [Usergroups.UserID] = @name AND [Groups.GroupID] = [Usergroups.GroupID]
这就是我将返回值放入DataTable的方法:
DataTable groupsTable = new DataTable(); groupsTable.Load(sqlCmd.ExecuteReader());
现在,我如何指定我DataTable
想从哪个表中获取行?例如,这是我在涉及的多个表之前所做的事情:
string groupName = groupsTable.Rows[0]["Name"];
我找不到任何有此类信息的资源,但我知道这是一个基本问题.提前致谢.
因此,您的问题中的查询不会产生多个表.
它在两个表之间产生JOIN.
因此,在C#端,您没有两个表,只有一个像以前一样,使用两个表中的所有字段.
作为旁注,将表连接在一起的更好方法是通过使用这样的JOIN语句
SELECT * -- a field list is better here --- FROM Usergroups ug INNER JOIN Groups g ON g.GroupID=ug.GroupID WHERE ug.UserID=@name
你应该在SELECT子句中添加一个你真正感兴趣的字段列表.
看一个简单的JOIN参考
如果要在单独的DataTable对象中检索两个表的值,则需要以这种方式使用DataSet
DataSet ds = new DataSet(); DataTable dtUserGroups = new DataTable("UserGroups"); DataTable dtGroups = new DataTable("Groups"); ds.Tables.Add(dtUserGroups ); ds.Tables.Add(dtGroups); using(SqlCommand cmd = new SqlCommand("SELECT * FROM UserGroups;SELECT * from Groups", con)) { using(SqlDataReader dr = cmd.ExecuteReader()) { ds.Load(dr, LoadOption.OverwriteChanges, dtUserGroups, dtGroups); // Now you have the two tables filled and // you can read from them in the usual way } }
最后一个示例可以进一步增强将DataRelation对象添加到DataSet以表示两个表之间的关系.这可以允许您的代码导航父/子记录集.