给定任何SELECT
语句,我想用skip包装并使用运算符。
例如,对于Oracle,我创建了这个函数:
public override string WrapSelectSqlWithPagination(string sql, int skipRows, int numberOfRows)
{
string innerSql = String.Format("select /* FIRST_ROWS(n) */ a.*, ROWNUM rnum from ({0}) a where ROWNUM <= {1}", sql, skipRows + numberOfRows);
return String.Format("select * from ({0}) where rnum > {1}", innerSql, skipRows);
}
效果很好。
我想为SQL Server做同样的事情,有可能吗?
请注意,我对提前排序一无所知。
感谢。
答案 0 :(得分:2)
您可以使用此sql模板获取所需的SQL记录范围。
WITH [AnyVariable] AS
(
select * ,ROW_NUMBER() over(order by [Col1]) AS 'RowNum'
from [Table1]
)
SELECT * FROM [AnyVariable]
WHERE RowNum BETWEEN 3 AND 6
用你的东西替换[]中的东西。记得删除[]。然后在上面的方法中使用它。
答案 1 :(得分:-1)
好的,我明白了。它可能很慢但是有效:
public override string WrapSelectSqlWithPagination(string sql, int skipRows, int numberOfRows) {
Regex regex = new Regex("SELECT", RegexOptions.IgnoreCase);
sql = regex.Replace(sql, "SELECT TOP 2147483647 ", 1);
string innerSql =
@"select * into #TempTable from (
select * ,ROW_NUMBER() over(order by aaa) AS rownum from (
select 'aaa' as aaa, * from (
{0}
)as t1
)as t2
) as t3
where rownum between {1} and {2}
alter table #TempTable drop column aaa
alter table #TempTable drop column rownum
select * from #TempTable
drop table #TempTable
";
return String.Format(innerSql, sql, skipRows+1, skipRows + numberOfRows);
}
有更好的方法吗?