存储过程(删除发票)

时间:2012-02-18 14:10:30

标签: sql sql-server stored-procedures

我正在尝试找出一种方法来创建用于从db中删除发票的存储过程。

三张桌子受到影响:

  • INVOICE - 包含InvoiceID,Date和CustomerID(fk)
  • INVOICELINE - 包含InvoicelineID,InvoiceID(fk),ArticleID(fk),数量,价格和折扣
  • 文章 - 包含带有文章名称,数量,价格和折扣的文章。

    这就是我想要的:

    1. 您使用一个参数InvoiceID
    2. 调用SP
    3. 发票行中的项目编号将添加回商品表格中,以添加到该商品的数量。
    4. 发票上的所有发票行都已删除
    5. 发票已删除

以下是我目前所拥有的,这是一个用于删除发票行的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

1 个答案:

答案 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