2015-11-03 42 views
1

我在我的SQL Server數據庫2個表,使用Visual Studio 2013(外鍵):SQL Server和2臺工作ASP.NET

  1. 類別

    • 編號
    • 名稱
  2. 產品

    • 編號
    • 名稱
    • 類別編號

我有建於ASP.NET(web表單)產品頁面中,我可以創建,編輯或刪除產品。

我在兩個表之間建立了連接(外鍵)。

我想顯示我的產品,而不是將類別作爲數字(Id)我想要它的名稱。

我應該怎麼做?

我在SQL方面的知識很基礎。

這是我真的如何顯示的代碼,使用一個DataList:

string SQL = "SELECT * FROM Products;"; 
SqlCommand cmd = new SqlCommand(SQL, conn); 
SqlDataAdapter adapter = new SqlDataAdapter(cmd); 
DataSet ds = new DataSet(); 
adapter.Fill(ds); 

dlProducts.DataSource = ds; 
dlProducts.DataBind(); 

謝謝了很多!

回答

0

您正在查找join

您的查詢看起來是這樣的:

select * 
from products p -- p is an "alias" for the table products 
inner join category c on p.categoryId = c.id -- here we're specifying that the products table to join onto the category table via their relationship columns. 

注意上面會返回更多的列比你需要什麼,你可以在*改變只返回所需的列(以及它通常被認爲是最好指定一個列表列表)

1

改變你的SELECT語句到這一點:

"SELECT p.Id, p.Name, c.Name FROM Product p, Category c WHERE p.CategoryId=c.Id;" 
+0

雖然這看起來會在技術上起作用,但我相信逗號「連接」通常是不被接受的,因爲它們是較舊的語法並且效率低下。有關更多信息,請參閱http://stackoverflow.com/a/129410/2312877。雖然也有一些關於它的無效的辯論:) – Kritner

1

加入到類別表,並從類別表的主要結果一起返回的名稱。

string SQL = "SELECT p.*, pc.Name FROM Products p 
       INNER JOIN ProductCategories pc 
       ON p.ProductCategoryID = pc.ProductCategoryID;"; 
+0

我想感謝你們所有人! 非常感謝你! – Peter