9

I need to create an SQL formatter in C#. Could anyone point me to some resources on the net? Do I need to implement a full-fledged parser, or is there an easier way to do it?

1
  • Is there an easier way to do it? Can't I format it without parsing? Commented Dec 22, 2009 at 8:18

4 Answers 4

6

Have a look at

Parsing SQL code in C#

Also hav a look at

Sql Pretty Printer

Sign up to request clarification or add additional context in comments.

Comments

4

Hmm, another question I'm stumbling across much later, but in case this is useful to anyone else down the line, I've implemented an open-source (AGPL) T-SQL formatter: http://www.architectshack.com/PoorMansTSqlFormatter.ashx

My approach definitely does not involve full SQL parsing (T-SQL is a very complex language, I don't rate my chances of developing and maintaining a complete parser on my own) but rather tokenizing and then identifying major structures in the SQL, by keyword. The result is a partial parse tree with all the formatting-relevant parts broken out.

As noted in answers to the question @astander linked to, there are commercial options for comprehensive SQL parsing, and lots of parser builders out there - but no complete open-source T-SQL parsers than I know of.

Making a parser for simple selects, updates, deletes is straightforward - handling derived tables and subqueries gets a little harder; then OUTPUT clauses, MERGE statements, multi-statement scripts, CTEs, the dozens of DDL statements T-SQL contains, etc: it gets messy.

3 Comments

This library worked really well for me, and there's a Nuget packed for it now too: nuget.org/packages/PoorMansTSQLFormatter
I went to git hub, downloaded the master and used the winform app.
Be aware that it's licensed under AGPL, so if you use it you have to open-source your own code.
3

When I am in a crunch and need to make something at least look "formatted", I jump to

http://www.dpriver.com/pp/sqlformat.htm

Comments

1

There is also the SQLinForm SQL beautifier which has a C# API at www.sqlinform.com

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.