我是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
使用Case When
语句在“fly”上生成ResultCategoryName。这是一个相当简单的查询。现在,如果您注意到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>'
并在生成实际SQL的if (_dbType == DBType.SqlServer || _dbType == DBType.Oracle)
内,我将其修改为:
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
这个有效!! :)。但是我需要知道这是否是正确的方法,或者有更好的方法来做到这一点。
答案 0 :(得分:3)
你所要做的就是用另一个选择包装你的sql。
例如
select * from (**your query here**) query order by ResultCategoryName asc
只有在计算完列后才需要执行此操作。