解析表名的SQL脚本

问题描述 投票:0回答:3

我想将SQL INSERT语句解析为object(表示为文本)。有一个SQL脚本文件包含:

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

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

以及更多的表插入。

解析表名称(Document,DocType,..)的最简单方法是什么?

如果我不想计算子串,可以使用RegEx吗?

const string pattern = @"INSERT INTO\s\w";

        foreach (var line in FileContent)
        {
            var a = Regex.Match(line, pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            if (a.Success)
            {

            }
        }
c# regex
3个回答
1
投票

而不是使用Regex并且可能错过了许多你没有考虑过的边缘情况,请看一下使用专用的SQL Parser。

有针对.NET的SQL解析器的several related问题。


0
投票

正则表达式做到了这一点

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);
}

0
投票

我有类似的问题,解析SQL文件并在Ruby上提出这个通用的Parser。它涵盖了所有案例并将扫描结果记录到文件中以供进一步审核。也可以调整其他类型。 Take R10.rb file from here

© www.soinside.com 2019 - 2024. All rights reserved.