2016-06-20 72 views
0

對不起,如果這將是一個愚蠢的問題,這是我第一次使用SQL存儲過程。問題很簡單 - 我如何聲明SELECT語句中的語句?爲了說明我的意思,這裏是一個代碼,我目前有:SQL存儲過程如果語句在選擇

INSERT INTO @trAll 
SELECT tr.EventDateTime 
    ,tr.OrderId 
    ,'EX' 
    ,round(tr.Prod01_CompB_QuantityPV_LTR + tr.Prod01_Fuel_QuantityPV_LTR,0) 
    ,tr.eAD 
    ,tr.OperatorName 
    -- 
    ,cmr.ConsigneeName 
    ,cmr.ConsigneeCompanyCode 
    ,cmr.SenderName 
    ,cmr.SenderCompanyCode 
FROM vwTransaction AS tr 
inner join tbOrderDetailCMR as cmr 
on tr.orderid = cmr.OrderId 
WHERE tr.EventDateTime BETWEEN @From 
     AND @to 
     AND ProductName = 'BIODIESELZ' 

這也是我需要什麼(希望你能明白我的意思):

INSERT INTO @trAll 
SELECT tr.EventDateTime 
    ,tr.OrderId 
    ,'EX' 
    ,round(tr.Prod01_CompB_QuantityPV_LTR + tr.Prod01_Fuel_QuantityPV_LTR+ (if (tr.Prod01_AdditiveA>0) THEN tr.Prod01_AdditiveA ELSE tr.Prod01_AdditiveB),0) 
    ,tr.eAD 
    ,tr.OperatorName 
    -- 
    ,cmr.ConsigneeName 
    ,cmr.ConsigneeCompanyCode 
    ,cmr.SenderName 
    ,cmr.SenderCompanyCode 
FROM vwTransaction AS tr 
inner join tbOrderDetailCMR as cmr 
on tr.orderid = cmr.OrderId 
WHERE tr.EventDateTime BETWEEN @From 
     AND @to 
     AND ProductName = 'BIODIESELZ' 

總之我需要的是添加AdditiveA(如果它的值大於0),否則AdditiveB在select語句中。

+1

哪些DBMS您使用的? –

回答

4

通過您所使用的語法我認爲這是T-SQL(微軟SQL服務器):

不能使用IF像這樣的語句內。使用CASE這裏,像這樣:

... 
,round(tr.Prod01_CompB_QuantityPV_LTR + tr.Prod01_Fuel_QuantityPV_LTR+ 
(CASE 
    WHEN (tr.Prod01_AdditiveA>0) THEN tr.Prod01_AdditiveA 
    ELSE tr.Prod01_AdditiveB 
END),0) 
... 

編輯:其實,現在我讀它,阿什溫Nairs答案,甚至更好。他使用IIF命令,這不太「侵入」。你可能想看看和/或接受他的答案。

3

假設你正在使用SQL服務器,請嘗試使用iif代替

INSERT INTO @trAll 
SELECT tr.EventDateTime 
,tr.OrderId 
,'EX' 
,round(tr.Prod01_CompB_QuantityPV_LTR + tr.Prod01_Fuel_QuantityPV_LTR+ iif(tr.Prod01_AdditiveA>0, tr.Prod01_AdditiveA, tr.Prod01_AdditiveB),0) 
,tr.eAD 
,tr.OperatorName 
-- 
,cmr.ConsigneeName 
,cmr.ConsigneeCompanyCode 
,cmr.SenderName 
,cmr.SenderCompanyCode 
FROM vwTransaction AS tr 
inner join tbOrderDetailCMR as cmr 
on tr.orderid = cmr.OrderId 
WHERE tr.EventDateTime BETWEEN @From 
    AND @to 
    AND ProductName = 'BIODIESELZ'