Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Formatter using C#

Tags:

c#

sql

parsing

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?

like image 530
BlueSilver Avatar asked Dec 22 '09 06:12

BlueSilver


People also ask

What is SQL Formatter?

The SQL Formatter is used with the purpose to beautify the SQL statements. It formats the code automatically and its working is based on simple algorithms. It formats the code based on easy rules and helps to write fancy SQL code.

Does prettier work with SQL?

Prettier code is easy to analyze and easy to maintain. The same principle applies to SQL queries.

How can I beautify code in mysql?

MYSQL Formatter allows loading the SQL URL to beautify. Use your SQL URL to beautify. Click on the URL button, Enter URL and Submit. Users can also beautify and remove the comments from SQL.


4 Answers

Have a look at

Parsing SQL code in C#

Also hav a look at

Sql Pretty Printer

like image 123
Adriaan Stander Avatar answered Sep 21 '22 12:09

Adriaan Stander


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.

like image 20
Tao Avatar answered Sep 19 '22 12:09

Tao


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

like image 24
RichardTheKiwi Avatar answered Sep 22 '22 12:09

RichardTheKiwi


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

like image 38
Guido Avatar answered Sep 23 '22 12:09

Guido