2016-06-10 44 views
1

我已經編寫了此存儲過程以將行項添加到名爲InvoiceLineItems的表中。數據庫確實有一些測試條目,並且此過程基於正在工作的其他插入存儲過程。用於插入的SQL Server存儲過程運行,但不會將值插入到表中

由於某種原因,查詢將會成功執行,但這些值實際上並未插入到表中,而且我無法弄清楚爲什麼,尤其是因爲其他插入過程已經奏效。

代碼,它成功地將值插入表:

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 

爲什麼它不插入值的任何想法:

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 

不插入值的代碼?

+1

你能格式化你的代碼嗎?這是臨界不可讀的。 –

+0

對不起,這是我第一次使用本網站。我將如何格式化它?當我打開它看起來是正確的,所以我不知道該怎麼做。 – BriMead

回答

1

IF...ELSE中,ELSE或補充IF僅在前面的IF語句不滿足時才執行。因此:

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

如果返回TRUE你的聲明會終止,你會設置了@ListPrice

您需要檢查所有的錯誤就像你在你的第一個聲明中所做的,如果所有條件都得不到滿足(沒有錯誤),然後設置你的變量和更新(插入)到表中。

+0

謝謝!老實說,我忘了這一點與IF語句,我一直在尋找了這麼久,它甚至不來的想法。但它現在起作用了!謝謝! – BriMead

+0

完全沒有後顧之憂! – scsimon

相關問題