Skip to content

Instantly share code, notes, and snippets.

@nielsbosma
Created January 23, 2019 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nielsbosma/d5425ca23df3f3d6ff20273b7a5efd54 to your computer and use it in GitHub Desktop.
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.
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