![](/img/trans.png)
[英]how to display data in data grid that is from joined tables and table 1 and two have columns with the same name
[英]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.