2012-11-02 57 views
1

考慮下面的SQL查詢:CASE在WHERE子句相當於

SELECT 
    * 
FROM 
    Orders 
WHERE 
    (AdjShipDate IS NOT NULL OR EstShipDate IS NOT NULL) 
    AND 
    CASE 
     WHEN AdjShipDate IS NOT NULL THEN AdjShipDate 
     WHEN AdjShipDate IS NULL AND EstShipDate IS NOT NULL THEN EstShipDate 
    END 
    BETWEEN '2011-07-01' AND '2011-07-30' 

的情況下,這時候表達依賴於從我試圖查詢表中的值(AdjShipDate)。我如何在Linq to SQL中編寫類似的查詢?

回答

1

它本質上是一個COALESCE:

where (o.AdjShipDate ?? o.EstShipDate) >= new DateTime(2011,07,01) 
    && (o.AdjShipDate ?? o.EstShipDate) <= new DateTime(2011,07,30) 

雖然我不能確定的?運算符由Linq-to-SQL支持。如果沒有,你可以嘗試

where (o.AdjShipDate != NULL 
      && o.AdjShipDate >= new DateTime(2011,07,01) 
      && o.AdjShipDate <= new DateTime(2011,07,30)) 
    || (o.AdjShipDate == NULL && o.EstShipDate != NULL 
      && o.EstShipDate >= new DateTime(2011,07,01) 
      && o.EstShipDate <= new DateTime(2011,07,30)) 
+0

+1和LINES to SQL支持COALESCE。只有一件事 - 你應該爲where語句添加'(o.AdjShipDate!= null || o.EstShipDate!= null)'。 –

+0

null-coalescing運算符在Linq-to-SQL中工作!謝謝! – Kerby

0

這是絕對等同於:

SELECT 
    * 
FROM 
    Orders 
WHERE 
    (AdjShipDate IS NOT NULL and AdjShipDate BETWEEN '2011-07-01' AND '2011-07-30') 
    OR 
    (AdjShipDate IS NULL and EstShipDate IS NOT NULL ANd EstShipDate BETWEEN '2011-07-01' AND '2011-07-30') 

它只是編譯成LinqToSql。