用于Insert运行的SQL Server存储过程,但不会将值插入表中

时间:2016-06-10 20:13:08

标签: sql-server stored-procedures

我已经编写了这个存储过程来将行项添加到名为InvoiceLineItems的表中。数据库确实有一些测试条目,此过程基于其他正在运行的插入存储过程。

由于某种原因,查询将成功执行,但这些值实际上并未插入到表中,我无法弄清楚原因,特别是因为其他插入过程已经有效。

成功将值插入表中的代码:

IF OBJECT_ID('sp_InsertInvoices') IS NOT NULL
    DROP PROC sp_InsertInvoices;
GO

CREATE PROC sp_InsertInvoices
     @CustomerID INT = NULL,
     @TotalDue MONEY = NULL,
     @Paid CHAR(3) = NULL
AS
BEGIN
    IF @CustomerID IS NULL
        THROW 50001, 'CustomerID cannot be null.', 1;

    IF @TotalDue IS NULL
        THROW 50001, 'TotalDue cannot be Null.', 1;

    IF @TotalDue < 0
        THROW 50001, 'TotalDue cannot be negative.', 1;

    IF @Paid IS NULL
        THROW 50001, 'Must specify if the balance is paid or not.', 1;
    ELSE --All data is validated
        INSERT INTO Invoices (CustomerID, TotalDue, Paid)
        VALUES (@CustomerID, @TotalDue, @Paid)
END
GO

不插入值的代码:

IF OBJECT_ID('sp_InsertInvoiceLineitems') IS NOT NULL
    DROP PROC sp_InsertInvoiceLineitems;
GO

CREATE PROC sp_InsertInvoiceLineitems
     @InvoiceID INT = NULL,
     @ProductID INT = NULL,
     @PQty TINYINT = NULL,
     @ListPrice MONEY = NULL, 
     @ServiceID INT = NULL,
     @ServiceCost MONEY = NULL, 
     @SQty TINYINT = NULL,
     @TotalAmount MONEY = NULL
AS
BEGIN
    IF @InvoiceID IS NULL
        THROW 50001, 'Must enter an InvoiceID.', 1;

    IF @ProductID IS NOT NULL AND @ProductID NOT IN (SELECT ProductID FROM Products)
        THROW 50001, 'Please enter a valid ProductID.', 1;

    IF @PQty IS NOT NULL AND @ProductID IS NOT NULL AND @PQty <= 0
        THROW 50001, 'PQty must be greater than zero.', 1;

    IF @ProductID IS NOT NULL
        SET @ListPrice = (SELECT ListPrice FROM Products WHERE ProductID = @ProductID);

    IF @ServiceID IS NOT NULL AND @ServiceID NOT IN (SELECT ServiceID FROM Services)
        THROW 50001, 'Please enter a valid ServiceID.', 1;

    IF @ServiceID IS NOT NULL
        SET @ServiceCost = (SELECT ServiceCost FROM Services WHERE ServiceID = @ServiceID);

    IF @SQty IS NOT NULL AND @ServiceID IS NOT NULL AND @Sqty <= 0
        THROW 50001, 'SQty must be greater than zero.', 1;

    IF @ProductID IS NOT NULL OR @ServiceID IS NOT NULL
        SET @TotalAmount = ((@ListPrice*@PQty) + (@ServiceCost*@SQty));
    ELSE --All data is verified
        INSERT INTO InvoiceLineItems (InvoiceID, ProductID, PQty, ListPrice, ServiceID, ServiceCost, SQty, TotalAmount)
        VALUES (@InvoiceID, @ProductID, @PQty, @ListPrice, @ServiceID, @ServiceCost, @SQty, @TotalAmount);
END
GO

有关为什么不插入值的任何想法?

1 个答案:

答案 0 :(得分:1)

IF...ELSE中,ELSE或补充IF仅在前一个IF语句不满足时执行。因此:

IF @ProductID IS NOT NULL SET @ListPrice = (SELECT ListPrice FROM Products WHERE ProductID = @ProductID)

如果此评估结果为TRUE,您的对帐单将终止,并且您将设置@ListPrice

您需要像在第一个语句中一样检查所有错误,如果不满足所有条件(没有错误),则设置变量并更新(插入)到表中。