0

我得到了一個這樣的SQL代碼,我將在.NET應用程序中使用它,我熟悉LINQ,但我不知道如何處理WITH語句。WITH LINQ Entity Framework中的語句

WITH records 
AS 
(
    SELECT [key], [rev], [IsCurrent], 
      ROW_NUMBER() OVER(PARTITION BY [key] 
      ORDER BY CASE WHEN [rev] = @revNUm   
      THEN 0 ELSE 1 END) rn 
    FROM tableName 
    WHERE [Rev] IN (@revNUm,0) 
) 
SELECT [key], [rev], [IsCurrent] 
FROM records 
WHERE rn = 1 

編輯:ROW_NUMBER()似乎很難以及,我該怎麼做?

感謝

+2

在數據庫中創建一個視圖並查詢它,而不是直接從LINQ進行相同的查詢。 – MarcinJuraszek

+1

你在WITH語句上阻塞很有趣。在你的地方,我會擔心ROW_NUMBER! –

回答

1

它看起來像你正在做的每一個關鍵組的第一個記錄,其中rev爲0或等於revnum參數。你可以做到這一點Linq中有:

var query = db.records 
       .OrderBy(r => r.rev == revNum ? 0 : 1) 
       .Where(r => rev == 0 || rev == revNum) 
       .GroupBy(r => r.key) 
       .Select(g => g.First()); 

如果記錄中包含更多的是,在查詢中的三個字段,然後只需添加

   .Select(r => new {r.key, r.rev, r.IsCurrent}) 
0

查詢保存爲一個存儲過程和使用LINQ,調用存儲過程(在這裏看到:http://msdn.microsoft.com/en-us/library/bb918119.aspx)。事情是這樣的:

CREATE PROCEDURE newprocedure 
@revNUm INT 
AS  
BEGIN 
WITH records 
AS 
(
    SELECT [key], [rev], [IsCurrent], 
      ROW_NUMBER() OVER(PARTITION BY [key] 
      ORDER BY CASE WHEN [rev] = @revNUm   
      THEN 0 ELSE 1 END) rn 
    FROM tableName 
    WHERE [Rev] IN (@revNUm,0) 
) 
SELECT [key], [rev], [IsCurrent] 
FROM records 
WHERE rn = 1 
END 
0

從代碼中創建內嵌表值函數

CREATE FUNCTION YourFunction 
( 
) 
RETURNS TABLE 
AS 
RETURN 
(
WITH records 
AS 
(
    SELECT [key], [rev], [IsCurrent], 
      ROW_NUMBER() OVER(PARTITION BY [key] 
      ORDER BY CASE WHEN [rev] = @revNUm   
      THEN 0 ELSE 1 END) rn 
    FROM tableName 
    WHERE [Rev] IN (@revNUm,0) 
) 
SELECT [key], [rev], [IsCurrent] 
FROM records 
WHERE rn = 1 
) 
GO 

將此功能放到您的DBML設計器中。這樣您將獲得最快的執行時間和最簡單的實現方式。