Parsing SQL script for table names

Parsing SQL script for table names



I would like to parse SQL INSERT statements into object (represented as a text). There is an SQL script file containing:


INSERT INTO Document(Id, Name, Description ...)
VALUES('DC001', 'FOO', 'bar');

INSERT INTO DocType(Id, Name)
VALUES('DT001', 'DOCX');



and many more table inserts.



What is the easiest way to parse out Table names (Document, DocType,..)?



Would it be possible with RegEx, if I don't wanna calculate substrings?


const string pattern = @"INSERT INTOsw";

foreach (var line in FileContent)

var a = Regex.Match(line, pattern, RegexOptions.Compiled




3 Answers
3



Instead of using Regex and probably missing out lots of edge cases you have not considered, look at using a dedicated SQL Parser.


Regex



There are several related questions for SQL parser for .NET.






This is all it is, no edge cases. All I need is Table names, Fields and Values in arrays.

– kayz1
Mar 7 '12 at 17:16






@kayz1 - I am talking about formatting edge cases, different ways of writing the required DML etc.

– Oded
Mar 7 '12 at 19:33






I agree with Oded, Regex is the poor man solution, it can and will break eventually, and down the road cause more costs than profit.

– Agustin Garzon
Feb 24 '16 at 12:47



Regex did the trick


private readonly IList<string> _tableList = new List<string>();

public const string TableName = @"s*(INSERT|UPDATE)s*(INTO|w+)s*(w+)s*((|VALUES|SET)";
public static readonly Regex ValidLine = new Regex(TableName, RegexOptions.Compiled | RegexOptions.IgnoreCase);

var currentTableName = ValidLine.Match(line);
var value = currentTableName.Groups[3].Value;

if (!_tableList.Contains(value))

_tableList.Add(value);



I had similar problem, parsing SQL files and come up with this universal Parser on Ruby.
It covered all cases and log scan result into file for further review. Can be adjusted for other types too.
Take R10.rb file from here



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế