Created
January 23, 2019 08:56
-
-
Save nielsbosma/d5425ca23df3f3d6ff20273b7a5efd54 to your computer and use it in GitHub Desktop.
Trick to transform the SQL that we get from Linqpad so it runs in Tableau and SQL management studio.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
TextWriter tw = new StringWriter(); | |
Log = tw; | |
Users.Where(e => ...).ToArray(); | |
tw.ToString().TransformSql().Dump(); | |
} | |
public static class MyExtensions | |
{ | |
public static string TransformSql(this string input) | |
{ | |
string[] lines = input.Split('\n').Select(e => e.Trim()).Where(e => !string.IsNullOrEmpty(e)).ToArray(); | |
string sql = string.Join(Environment.NewLine, lines.Where(e => !e.StartsWith("--")).ToArray()); | |
string[] comments = lines.Where(e => e.StartsWith("--")).ToArray(); | |
foreach (string comment in comments) | |
{ | |
var regex = new Regex(@"^-- (@p\d+): Input (?:\w+)[^/[]*\[(.*)]"); | |
var match = regex.Match(comment); | |
if (match.Success) | |
{ | |
string variable = match.Groups[1].Value; | |
string value = match.Groups[2].Value; | |
sql = sql.Replace(variable, double.TryParse(value, out _) ? value : $"'{value}'"); | |
} | |
} | |
return sql; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment