繁体   English   中英

当不同表中的两列具有相同名称时,如何使用SqlDataReader读取数据?

[英]How to read data using SqlDataReader when two columns in different tables have same name?

我在两个不同的表中有两个名为“名称”的列。 一个在商店表中,另一个在产品表中。 我该如何区分阅读哪一个?

数据使用左连接从4个不同的表中获取,如下查询所示。

var conn = new SqlConnection("serverinfo");
SqlCommand query = new SqlCommand("SELECT Store.StoreID, Store.Name, 
Product.Name, " +
" StockRequest.Quantity, StoreInventory.StockLevel from Store" +
" LEFT JOIN StoreInventory ON StoreInventory.StoreID = Store.StoreID" 
+ " LEFT JOIN Product ON StoreInventory.ProductID = 
Product.ProductID" + " LEFT JOIN StockRequest ON StockRequest.StoreID 
= Store.StoreID", conn);

SqlDataReader read;

        try {
            conn.Open();
            read = query.ExecuteReader();
            while (read.Read()) {
                Console.WriteLine("{0} {1} {2} {3} {4}",
                                  read["StoreID"],
                                  read["Name"],
                                  read["Name"],
                                  read["Quantity"],
                                  read["StockLevel"]);

            }
            conn.Close();
            } catch (Exception e) {}

表名称是商店,产品,库存请求,商店库存。

现在,两个“名称”列的数据都来自“存储”表。 我无法从“产品”表中获取“名称”数据。

您可以使用别名为重复的列命名。

SqlCommand query = new SqlCommand("SELECT Store.StoreID, 
"Store.Name as StoreName," + 
"Product.Name as ProductName," +
" StockRequest.Quantity, StoreInventory.StockLevel from Store" +
" LEFT JOIN StoreInventory ON StoreInventory.StoreID = Store.StoreID" 
+ " LEFT JOIN Product ON StoreInventory.ProductID = 
Product.ProductID" + " LEFT JOIN StockRequest ON StockRequest.StoreID 
= Store.StoreID", conn);

然后在阅读时使用正确的名称即可,例如:

read["StoreID"],
read["StoreName"], read["ProductName"],
read["Quantity"], read["StockLevel"]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM