我在编写SQL Server存储过程时遇到一些问题。我有三张表,Products
、CustomerInfo
和CustomerOrders
。
Products
具有列ProductID,Product, Price, Description
CustomerInfo
有列CostumerID, Name, Address, Zipcode
CustomerOrders
具有与CustomerID or TransactionID, ProductID, Quantity
类似的列
现在我正试图编写一个存储过程,将客户购买过的所有产品导入到数据表中。我有可以用作参数的客户名称。
需要注意的几点是:每次客户购买东西时,都会生成一个新的CustomerID
和TransactionID
,它们都是相同的。CustomerName
是多个订单中唯一的常量。
DECLARE @TransactionID int;
SET @TransactionID = @Id;
SELECT
P.Product, P.Price,
CP.TotalProducts as ProductQuantity
FROM
Products P
INNER JOIN
CustomerProducts CP ON CP.ProductID = P.ProductID
WHERE
CP.CustomerID = @TransactionID
目前,我得到的是顾客上次购物时买的产品。然而,我想把他买过的所有产品都放在一张桌子上。如果有人能帮我,我真的很感激!
如果我理解正确,您需要连接存储过程中的3个表,以提取客户购买产品的所有详细信息。
因此,用于此目的的存储过程可能看起来像这样-
CREATE PROC [dbo].[GetCustomerProductsById]
(
@CustId int=0
AS
BEGIN
SELECT P.ProductId ,P.Product,P.Price,P.Description,C.CustomerID,C.Name,C.Address FROM Products P
Inner Join CustomerOrders CO ON P.ProductId= CO.ProductID
Inner Join CustomerInfo C ON C.CustomerID = CO.CustomerID
WHERE C.CustomerID = @CustId
ORDER BY C.Name
END
现在,一旦这给了我们预期的结果,那么在c#代码中,您可以调用下面这样的存储过程,并提取一个结果数据表。
SqlDataAdapter SqlAda;
DataSet ds;
using (SqlConnection Sqlcon = new SqlConnection(strCon))
{
using (SqlCommand cmd = new SqlCommand())
{
Sqlcon.Open();
cmd.Connection = Sqlcon;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetCustomerProductsById";
cmd.Parameters.Add(new SqlParameter("@CustId", SqlDbType.Int, 50));
cmd.Parameters["@CustId"].Value = <Your Input Source>;
SqlAda = new SqlDataAdapter(cmd);
ds = new DataSet();
SqlAda.Fill(ds);
Datatable dt = new DataTable();
dt = ds.Tables[0];
}
}