简体   繁体   中英

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.

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"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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