2011-10-31 74 views
0

我有以下SQL:我應該在哪裏放置IF塊SQL命令

DECLARE @ActualFromDT DATETIME, 
     @ActualToDT DATETIME 

IF (ManPowerUsage.FromDT >= Shift.FromDT) 
    SET @ActualFromDT = ManPowerUsage.FromDT 
ELSE 
    SET @ActualFromDT = Shift.FromDT 

IF (ManPowerUsage.ToDT <= Shift.ToDT) 
    SET @ActualToDT = ManPowerUsage.ToDT 
ELSE 
    SET @ActualToDT = Shift.ToDT 

SELECT Shift.ShiftID, 
     Line.Line, 
     (SELECT SUM(DATEDIFF(MINUTE, @ActualFromDT, @ActualToDT)) 
      /DATEDIFF(MINUTE, Shift.FromDT, Shift.ToDT) 

     FROM ManPowerUsage 

     WHERE ManPowerUsage.LineID = Line.LineID 
      AND ((Shift.FromDT < ManPowerUsage.FromDT AND Shift.ToDT > ManPowerUsage.FromDT) 
       OR (Shift.FromDT < ManPowerUsage.ToDT AND Shift.ToDT > ManPowerUsage.ToDT )) 
      AND ManPowerUsage.IsEdited = 0 
     ) AS ActualManpower 
FROM ...... 

的命令顯然是行不通的,但我想知道我怎麼去了解我之前設置的參數做DATEDIFF s

回答

2

沒有。您可以使用CASE expression爲「內聯IF」

SELECT Shift.ShiftID, 
    Line.Line, 
    (SELECT SUM(DATEDIFF(MINUTE, 
       CASE 
        WHEN ManPowerUsage.FromDT >= Shift.FromDT 
         THEN ManPowerUsage.FromDT 
        ELSE Shift.FromDT 
       END, 
       CASE 
        WHEN ManPowerUsage.ToDT <= Shift.ToDT 
         THEN ManPowerUsage.ToDT 
        ELSE Shift.ToDT 
       END)) 
     /DATEDIFF(MINUTE, Shift.FromDT, Shift.ToDT) 
... 
0

你不應該需要任何變量,這樣的事情應該做的伎倆。儘管沒有完整的模式樣本,SQL片段不可測試。

SELECT 
Shift.ShiftID, 
Line.Line, 
(SELECT SUM 
    (
     DATEDIFF 
     (
      MINUTE, 
      case when mpu.FromDT>Shift.FromDt then mpu.FromDT else Shift.FromDt end, 
      case when mpu.ToDT<=Shift.ToDt then mpu.ToDT else Shift.ToDt end 
     ) 
    ) 
/DATEDIFF(MINUTE, Shift.FromDT, Shift.ToDT) 
FROM ManPowerUsage mpu 
WHERE mpu.LineID = Line.LineID 
AND (
    ( Shift.FromDT < mpu.FromDT 
     AND Shift.ToDT > mpu.FromDT 
    ) 
    OR ( Shift.FromDT < mpu.ToDT 
      AND Shift.ToDT > mpu.ToDT 
     ) 
    ) 
AND mpu.IsEdited = 0 
) AS ActualManpower 

FROM ......