Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
61 lines (52 loc) · 2.19 KB

File metadata and controls

61 lines (52 loc) · 2.19 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Simple.Data.Ado;
namespace Simple.Data.SqlServer
{
[Export(typeof(IQueryPager))]
public class SqlQueryPager : IQueryPager
{
private static readonly Regex ColumnExtract = new Regex(@"SELECT\s*(.*)\s*(FROM.*)", RegexOptions.Multiline | RegexOptions.IgnoreCase);
public string ApplyPaging(string sql, string skipParameterName, string takeParameterName)
{
var builder = new StringBuilder("WITH __Data AS (SELECT ");
var match = ColumnExtract.Match(sql);
var columns = match.Groups[1].Value.Trim();
var fromEtc = match.Groups[2].Value.Trim();
builder.Append(columns);
var orderBy = ExtractOrderBy(columns, ref fromEtc);
builder.AppendFormat(", ROW_NUMBER() OVER({0}) AS [_#_]", orderBy);
builder.AppendLine();
builder.Append(fromEtc);
builder.AppendLine(")");
builder.AppendFormat("SELECT {0} FROM __Data WHERE [_#_] BETWEEN {1} + 1 AND {1} + {2}", DequalifyColumns(columns),
skipParameterName, takeParameterName);
return builder.ToString();
}
private static string DequalifyColumns(string original)
{
var q = from part in original.Split(',')
select part.Substring(Math.Max(part.LastIndexOf('.') + 1, part.LastIndexOf('[')));
return string.Join(",", q);
}
private static string ExtractOrderBy(string columns, ref string fromEtc)
{
string orderBy;
int index = fromEtc.IndexOf("ORDER BY", StringComparison.InvariantCultureIgnoreCase);
if (index > -1)
{
orderBy = fromEtc.Substring(index).Trim();
fromEtc = fromEtc.Remove(index).Trim();
}
else
{
orderBy = "ORDER BY " + columns.Split(',').First().Trim();
}
return orderBy;
}
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.