【问题标题】:C# datatable from sql join 2 columns same name来自sql的C#数据表连接2列同名
【发布时间】:2009-08-07 07:33:09
【问题描述】:

我有一个这样的 sql 选择,它返回一个数据表:

select * from table1 a join table2 b on a.id=b.id

table1 和 table2 都有一个名为 itemno 的列。

如何引用 2 个单独的列?通常我会使用类似的东西:

datarow["itemno"].ToString(); <=first column named itemno only
datarow["b.itemno"].ToString(); <= fail

但是,这似乎只获得了名为 itemno 的第一列。
有没有办法在不更改我的 sql 语句的情况下引用名为 itemno 的第二列? (我知道我可以更改我的 sql 语句,取出 * 并放入列别名)。

【问题讨论】:

    标签: c# sql winforms


    【解决方案1】:

    您可以改为按索引引用列:

    datarow[0].ToString();
    

    说实话,我更喜欢给它们起别名。

    【讨论】:

    • 这里隐藏着危险。如果您稍后稍微更改查询并且它将开始以不同的顺序返回列,您的代码将停止工作。
    • 好点NewInTown。别名是迄今为止最好的方法。
    • SQL 语句中的别名?这是一个很长的 sql 语句,有很多列。我想这是我唯一的选择,因为我宁愿不使用数字索引。我不敢相信没有办法在 ADO/C# 中引用同名的列。
    • 是的。通常最好列出要返回的特定列,以防止返回不必要的数据,并可以提高查询性能。因此,最好考虑一下是否需要返回所有列。
    【解决方案2】:

    给定这样的 SQL 查询

    select a.id, b.id, a.columnA,a.columnB,a.itemno,b.itemno 
    from table1 a
    join table2 b on a.id=b.id
    

    您的 C# 代码将/可能看起来像这样来读取所有行和所有列:

    using (SqlCommand getAllColumns = new SqlCommand("select a.id, b.id,a.columnA,a.columnB,a.itemno,b.itemno from table1 a join table2 b on a.id=b.id", conn))
                        {
                            using (var drreader = getAllColumns.ExecuteReader())
                            {
                                DataTable tb = new DataTable();
                                tb.BeginLoadData();
                                tb.Load(drreader);
                                tb.EndLoadData();
                                foreach(DataRow row in tb.Rows.Cast<DataRow>().ToList())
                                {
                                     // assuming these are all varchar columns
                                     string idA = (string)row["id"];
                                     string idB = (string)row["id1"];
                                     string columnA = (string)row["columnA"];
                                     string columnB = (string)row["columnB"];
                                     string columnAItemNo = (string)row["itemno"]; //fetches the first itemno column, a.itemno in this case
                                     string columnBItemNo = (string)row["itemno1"]; //fetches the second itemno column, b.itemno in this case
                                     
                                }
                            }
                        }
    

    我在 .NET Framework 4.5 上使用它。如果您想验证或调试它,请在foreach 行上放置一个断点并检查DataTable 对象。第二个itemno 列的标题应该与第一个不同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-09
      • 1970-01-01
      • 2015-07-31
      • 1970-01-01
      相关资源
      最近更新 更多