0

我有一个这样的 SQL 代码,我将在 .NET 应用程序中使用它,我熟悉 LINQ,但我不知道如何处理 WITH 语句。

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() 似乎也很难,我该怎么做?

谢谢

4

3 回答 3

1

看起来您正在获取每个键分组中的第一条记录,其中rev0 或等于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})
于 2013-04-12T13:51:05.700 回答
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
于 2013-04-12T13:42:52.883 回答
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 设计器。这样您将获得最快的执行时间和最简单的实现方式。

于 2013-04-12T15:25:16.417 回答