一、安装包
PoorMansTSqlFormatterLib
二、代码实现
using Microsoft.AspNetCore.Mvc;
using PoorMansTSqlFormatterLib.Formatters;
using PoorMansTSqlFormatterLib.Parsers;
using PoorMansTSqlFormatterLib.Tokenizers;
namespace SaaS.OfficialWebSite.Web.Controllers
{
public class SqlFormatController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult FormatSql([FromBody] FormatRequest request)
{
try
{
var options = new TSqlStandardFormatterOptions
{
IndentString = request.Options.IndentWithTabs ? "\t" : " ",
SpacesPerTab = 4,
MaxLineWidth = 999,
KeywordStandardization = request.Options.UppercaseKeywords,
TrailingCommas = request.Options.TrailingCommas,
SpaceAfterExpandedComma = request.Options.SpaceAfterExpandedComma,
ExpandCommaLists = true,
ExpandBooleanExpressions = true,
ExpandCaseStatements = true,
ExpandBetweenConditions = true,
ExpandInLists = true,
BreakJoinOnSections = true,
UppercaseKeywords = request.Options.UppercaseKeywords
};
var tokenizer = new TSqlStandardTokenizer();
var parser = new TSqlStandardParser();
var formatter = new TSqlStandardFormatter(options);
var tokenized = tokenizer.TokenizeSQL(request.Sql);
var parsed = parser.ParseSQL(tokenized);
var formattedSql = formatter.FormatSQLTree(parsed);
return Ok(new { formattedSql });
}
catch (Exception ex)
{
return BadRequest(new { error = ex.Message });
}
}
}
public class FormatRequest
{
public string Sql { get; set; }
public FormatOptions Options { get; set; }
}
public class FormatOptions
{
public bool IndentWithTabs { get; set; }
public bool UppercaseKeywords { get; set; }
public bool TrailingCommas { get; set; }
public bool SpaceAfterExpandedComma { get; set; }
}
}
运行效果:SQL 语句格式化