SqlGenerator_OffsetFetch.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using Ant.DbExpressions;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. namespace Ant.SqlServer
  7. {
  8. class SqlGenerator_OffsetFetch : SqlGenerator
  9. {
  10. /// <summary>
  11. /// SQL2012实现分页
  12. /// </summary>
  13. /// <param name="exp"></param>
  14. protected override void BuildLimitSql(DbExpressions.DbSqlQueryExpression exp)
  15. {
  16. //order by number offset 10 rows fetch next 20 rows only;
  17. this._sqlBuilder.Append("SELECT ");
  18. List<DbColumnSegment> columns = exp.ColumnSegments;
  19. for (int i = 0; i < columns.Count; i++)
  20. {
  21. DbColumnSegment column = columns[i];
  22. if (i > 0)
  23. this._sqlBuilder.Append(",");
  24. this.AppendColumnSegment(column);
  25. }
  26. this._sqlBuilder.Append(" FROM ");
  27. exp.Table.Accept(this);
  28. this.BuildWhereState(exp.Condition);
  29. this.BuildGroupState(exp);
  30. List<DbOrdering> orderings = exp.Orderings;
  31. if (orderings.Count == 0)
  32. {
  33. DbExpression orderingExp = DbExpression.Add(UtilConstants.DbParameter_1, DbConstantExpression.Zero, DbConstantExpression.Zero.Type, null);
  34. DbOrdering ordering = new DbOrdering(orderingExp, OrderType.Asc);
  35. orderings = new List<DbOrdering>(1);
  36. orderings.Add(ordering);
  37. }
  38. this.BuildOrderState(orderings);
  39. this._sqlBuilder.Append(" OFFSET ", exp.SkipCount.Value.ToString(), " ROWS");
  40. if (exp.TakeCount != null)
  41. {
  42. this._sqlBuilder.Append(" FETCH NEXT ", exp.TakeCount.Value.ToString(), " ROWS ONLY");
  43. }
  44. }
  45. }
  46. }