0
我已聲明一個表變量@OpeningTable
。我想使用Insert Select插入一些基於某些條件的值。我寫這在下文中給出一個說法:基於IF條件插入選擇表變量
DECLARE @OpeningTable TABLE
(
ItemID INT, OpeningBalance DECIMAL(15,3)
)
INSERT INTO @OpeningTable
SELECT
IF EXISTS (SELECT ItemID, OpeningBalance FROM str_stockdaily WHERE stockdate = @FromDate AND (JobOrderid = @JobOrderID OR @JobOrderID = -1) AND (CustomerID = @CustomerID OR @CustomerID = -1) AND (ItemID = @ItemID OR @ItemID = -1))
SELECT ItemID, OpeningBalance FROM str_stockdaily WHERE stockdate = @FromDate AND (JobOrderid = @JobOrderID OR @JobOrderID = -1) AND (CustomerID = @CUstomerID OR @CustomerID=-1) AND (ItemID = @ItemID OR @ItemID = -1)
ELSE
IF EXISTS (SELECT ItemID FROM str_stockdaily WHERE stockdate = ISNULL((SELECT MAX(stockdate) FROM str_stockdaily WHERE stockdate < @FromDate AND (JobOrderid = @JobOrderID OR @JobOrderID = -1) AND (CustomerID = @CUstomerID OR @CustomerID = -1) AND (ItemID = @ItemID OR @ItemID = -1)), 0) AND (JobOrderid = @JobOrderID OR @JobOrderID = -1) AND (CustomerID = @CUstomerID OR @CustomerID = -1) AND (ItemID = @ItemID OR @ItemID = -1))
SELECT ItemID, closingbalance AS OpeningBalance FROM str_stockdaily WHERE stockdate = (SELECT MAX(stockdate) FROM str_stockdaily WHERE stockdate = @FromDate AND (JobOrderid = @JobOrderID OR @JobOrderID = -1) AND (CustomerID = @CUstomerID OR @CustomerID = -1) AND (ItemID = @ItemID OR @ItemID = -1)) AND (JobOrderid = @JobOrderID OR @JobOrderID = -1) AND (CustomerID = @CUstomerID OR @CustomerID = -1) AND (ItemID = @ItemID OR @ItemID = -1)
ELSE
SELECT ItemID, 0.000 AS OpeningBalance FROM str_item
但它給人的錯誤:
"Incorrect syntax near the keyword 'IF'
我不知道我是否已經寫了正確的查詢與否。如何解決這個問題呢?請我需要您的建議..
使用MERGE語句http://technet.microsoft.com/en-us/library/bb510625.aspx –