如何在修改该数据库的任何一个表时更新数据库的多个表的记录

时间:2011-03-01 05:38:41

标签: c# .net-3.5

我正在创建一个基于医疗库存的C#Windows应用程序。在此应用程序中,我主要有三种形式,如PurchaseDetail,SalesDetail和StockDetail。

现在我想要一个功能,如果我在PurchaseDetail或SalesDetail中插入或修改记录,那么StockDetail中的数据也应该被修改。(例如,如果我在PurchaseDetail中插入一定数量的药物,那么该药物的数量在StockDetail中也应该修改,与SalesDetail相同)

PurchaseDetail中的列:Id(主键和自动增量int),BatchNumber,ProductName,ManufacturingDate,ExpiryDate,Rate,MRP,Tax,Discount,Quantity

SalesDetail中的列:Id(PrimaryKey和自动增量int),BillNumber,CustomerName,BatchNumber,Quantity,Rate,SalesDate

StockDetail中的列:Id(主键和自动增量int),ProductId,ProductName,OpeningStock,ClosingStock,PurchaseQty,DispenseQty,PurchaseReturn,DispenseReturn

请帮助我提供任何合适的示例或代码

2 个答案:

答案 0 :(得分:0)

您可以轻松编写以分号“;”

分隔的多个SQL语句

示例:

INSERT INTO PurchaseDetail (BatchNumber, ProductID, Quantity) VALUES (@BatchNumber, @ProductID, @Quantity);
INSERT INTO StockDetail (ProductID, ProductName, OpeningStock, ClosingStock, PurchaseQty, DispenseQty, PurchaseReturn,DispenseReturn) SELECT ProductID, ProductName, ClosingStock, ClosingStock + @Quantity, @Quantity, 0, 0, 0 FROM StockDetail WHERE ProductID = @ProductID AND ID = (SELECT TOP 1 ID FROM StockDetail WHERE ProductID = @ProductID ORDER BY ID)

你真的不应该在每个表中再次存储产品名称。相反,您应该存储ProductID。您的SalesDetails没有说明销售的产品。

以下是更加规范化的建议架构:

产品(ID,ProductName,Stock) PurchaseDetail(ID,BatchID,ProductID,Quantity,...) SalesDetail(ID,BillID,ProductID,Quantity,...) PurchaseBatch(ID,PurchaseDate) SalesBill(ID,SalesDate,CustomerID)

如果您需要知道特定时间的开放,关闭,购买和分发,您始终可以运行SQL:

当前股票:

SELECT Stock FROM Product WHERE ID = @ProductID

从@StartDate购买到@EndDate:

SELECT SUM(Quantity) FROM PurchaseDetail INNER JOIN PurchaseBatch ON PurchaseDetail.BatchID = PurchaseBatch.ID WHERE PurchaseBatch.PurchaseDate >= @StartDate AND PurchaseBatch.PurchaseDate < @EndDate AND PurchaseDetail.ProductID = @ProductID

从@StartDate卖给@EndDate:

SELECT SUM(Quantity) FROM SalesDetail INNER JOIN SalesBill ON SalesDetail.BillID = SalesBill.ID WHERE SalesBill.SalesDate >= @StartDate AND SalesBill.SalesDate < @EndDate AND SalesDetail.ProductID = @ProductID

从@EndDate购买至今:

SELECT SUM(Quantity) FROM PurchaseDetail INNER JOIN PurchaseBatch ON PurchaseDetail.BatchID = PurchaseBatch.ID WHERE PurchaseBatch.PurchaseDate >= @EndDate AND PurchaseDetail.ProductID = @ProductID

从@EndDate销售至今:

SELECT SUM(Quantity) FROM SalesDetail INNER JOIN SalesBill ON SalesDetail.BillID = SalesBill.ID WHERE SalesBill.SalesDate > @EndDate AND SalesDetail.ProductID = @ProductID

因此,

从@StartDate开始直到@EndDate =    目前的股票   - 从@StartDate购买到@EndDate   - 从@EndDate购买至今  +从@StartDate到@EndDate的销售  + @EndDate到现在的销售

从@StartDate关闭直到@EndDate =    目前的股票   - 从@EndDate购买至今  + @EndDate到现在的销售

你也有  从@StartDate到@EndDate的销售  从@StartDate购买到@EndDate

答案 1 :(得分:0)

尝试使用Triggers.