[英]How to read data using SqlDataReader when two columns in different tables have same name?
I have two columns named 'Name' in two different tables. 我在两个不同的表中有两个名为“名称”的列。 One is in the Store table the other is in the Product table.
一个在商店表中,另一个在产品表中。 How do I differentiate which one is read?
我该如何区分阅读哪一个?
The data is taken from 4 different tables using left joins as shown in the query below. 数据使用左连接从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) {}
The table names are Store, Product, StockRequest, StoreInventory. 表名称是商店,产品,库存请求,商店库存。
Right now the data for both of the 'Name' columns are taken from the Store table. 现在,两个“名称”列的数据都来自“存储”表。 I am unable to take the 'Name' data from the Product table.
我无法从“产品”表中获取“名称”数据。
You could use alias to give a different name to the duplicate column. 您可以使用别名为重复的列命名。
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);
Then just use the right name when reading it, like: 然后在阅读时使用正确的名称即可,例如:
read["StoreID"],
read["StoreName"], read["ProductName"],
read["Quantity"], read["StockLevel"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.