1

我是 PetaPoco 的忠实粉丝,当我看到其中编写的代码时,我感到非常惊讶。但是,在将它用于现实生活项目时,我遇到了一个问题,其中我有一个类似这样的查询:

SELECT  em.SysEmailID, 
        [DisplayID], 
         Case When em.SysEmailCategoryID IS NULL Then em.CategoryName Else cat.CategoryName End as 'ResultCategoryName',
         [Name], 
         IsActive, 
         em.ModifiedDateTime, 
         us.Username  
            FROM [dbo].[SysEmail] em 
                Left JOIN dbo.Users us ON em.CreatedBy = us.UserID  
                    Left JOIN dbo.SysEmailCategory cat on em.SysEmailCategoryID = cat.SysEmailCategoryID 

ResultCategoryName 是用Case When语句“飞”生成的。这是一个相当简单的查询。现在,如果您曾经注意到用 PetaPoco 编写的代码,您会看到它包含了您的语句并附加了行号函数。所以你的查询变成:

SELECT * FROM 
    (
        SELECT ROW_NUMBER() OVER (ORDER BY ResultCategoryName desc) peta_rn,
         em.SysEmailID, 
         [DisplayID], 
         Case When em.SysEmailCategoryID IS NULL Then em.CategoryName Else cat.CategoryName End as 
         'ResultCategoryName',
         [Name], 
         IsActive, 
         em.ModifiedDateTime, 
         us.Username  
            FROM [dbo].[SysEmail] em Left JOIN dbo.Users us ON em.CreatedBy = us.UserID  
                Left JOIN dbo.SysEmailCategory cat on em.SysEmailCategoryID = cat.SysEmailCategoryID 

     ) peta_paged WHERE peta_rn>0 AND peta_rn<=10

发生这种情况时,您会收到 Sql 错误Invalid column name“ResultCategoryName”。我修改了方法'BuildPageQueries<T>',在if (_dbType == DBType.SqlServer || _dbType == DBType.Oracle)生成实际 SQL 的地方,我将其修改为:

 sqlPage = string.Format("SELECT * FROM (SELECT ROW_NUMBER() OVER ({0}) peta_rn, peta_query.* From (Select {1}) as peta_query) peta_paged WHERE peta_rn>@{2} AND peta_rn<=@{3}",
                                        sqlOrderBy == null ? "ORDER BY (SELECT NULL)" : sqlOrderBy, sqlSelectRemoved, args.Length, args.Length + 1);

这产生了查询:

SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY ResultCategoryName asc) peta_rn, 
    peta_query.* 
        From (
                Select em.SysEmailID, [DisplayID], 
                Case When em.SysEmailCategoryID IS NULL Then em.CategoryName Else cat.CategoryName End as 'ResultCategoryName',
                [Name], 
                IsActive, 
                em.ModifiedDateTime, 
                us.Username  
                    FROM [dbo].[SysEmail] em Left JOIN dbo.Users us ON em.CreatedBy = us.UserID  
                        Left JOIN dbo.SysEmailCategory cat on em.SysEmailCategoryID = cat.SysEmailCategoryID 
                            ) as peta_query) peta_paged WHERE peta_rn>0 AND peta_rn<=10

这行得通!:)。但是我需要知道这是否是正确的方法,或者有没有更好的方法。

4

1 回答 1

3

您所要做的就是用另一个选择包装您的 sql。

例如。

select * from (**your query here**) query order by ResultCategoryName asc

只有在计算列时才需要这样做。

于 2012-04-28T13:20:05.580 回答