多表關聯查詢可用 Correlated Subquery 或 JOIN。TableAdapter 精靈若偵測主查詢含 JOIN,不會自動產生 InsertCommand/UpdateCommand/DeleteCommand。本文比較兩種寫法、分析限制與因應策略。
SELECT ProductID, ProductName, ...,
(SELECT CategoryName FROM Categories WHERE Categories.CategoryID = Products.CategoryID) as CategoryName,
(SELECT CompanyName FROM Suppliers WHERE Suppliers.SupplierID = Products.SupplierID) as SupplierName
FROM Products
SELECT ProductID, ProductName, Products.SupplierID, Products.CategoryID, ...,
Categories.CategoryName,
Suppliers.CompanyName as SupplierName
FROM Products
LEFT JOIN Categories ON Categories.CategoryID = Products.CategoryID
LEFT JOIN Suppliers ON Suppliers.SupplierID = Products.SupplierID
JOIN 是關聯查詢首選,但需配合手動 CUD 設定或 Stored Procedure 架構。理解 TableAdapter 精靈限制,能在設計階段做正確技術選型。