我在编写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];
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句