我正在尝试找出一种方法来创建用于从db中删除发票的存储过程。
三张桌子受到影响:
文章 - 包含带有文章名称,数量,价格和折扣的文章。
这就是我想要的:
以下是我目前所拥有的,这是一个用于删除发票行的SP。我希望从名为DeleteInvoice的SP调用此SP。问题是我无法弄清楚SP应该如何设计才能使这项工作成为可能,例如如何循环开发票上的发票行?如果有人能帮到这里,我会很高兴。
用于删除发票行的SP(应从正在删除发票的SP调用,有发票行的次数):
@InvoiceID int
AS
BEGIN
DECLARE @Articleid int, @Quantity int
SELECT @Articleid = ArticleID, @Quantity=Quantity
FROM InvoiceLine
WHERE InvoiceID=@InvoiceID
BEGIN TRY
BEGIN TRAN
UPDATE Article SET Quantity=Quantity+@Quantity
WHERE ArtikelID=@Articleid;
DELETE FROM InvoiceLine
WHERE InvoiceLineID=@InvoiceLineID;
COMMIT TRAN
END TRY
BEGIN CATCH
ROLLBACK TRAN
RAISERROR ('Couldn't delete the invoice line!',16,1)
END CATCH
END
答案 0 :(得分:2)
我假设您在CREATE/ALTER PROCEDURE
声明之前故意切断@InvoiceID
行。您可以在事务中使用三个语句执行此操作 - 无需多个过程或循环:
@InvoiceID int
AS
BEGIN
BEGIN TRY
BEGIN TRANSACTION;
-- This reclaims inventory to the Article table
WITH R AS (
SELECT ArticleID, SUM(Quantity) ReclaimedQuantity
FROM InvoiceLine
WHERE InvoiceID = @InvoiceID
GROUP BY ArticleID
)
UPDATE Article
SET Quantity = Quantity + R.ReclaimedQuantity
FROM Article INNER JOIN
R ON Article.ArticleID = R.ArticleID;
-- Removes invoice line items
DELETE FROM InvoiceLine
WHERE InvoiceID = @InvoiceID;
-- Removes the invoice header item
DELETE FROM Invoice
WHERE InvoiceID = @InvoiceID;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION;
END CATCH
END