使用 C# 从 SQL CREATE 脚本中提取表名和列名

本文关键字:提取 脚本 SQL CREATE 使用 | 更新日期: 2023-09-27 18:36:28

问题:

从一行 SQL 脚本中提取表名和列名:

CREATE TABLE [ dbo ] . [ worktype_template ] ( [ worktype_key ] [ int ] NULL , [ template_key ] [ int ] NULL ) ON [ PRIMARY ]

我尝试过许多正则表达式,但惨败。任何建议,特别是在 C# 中,都会有所帮助。

使用 C# 从 SQL CREATE 脚本中提取表名和列名

这有效:

String query = "CREATE TABLE [ dbo ] . [ worktype_template ] ( [ worktype_key ] [ int ] NULL , [ template_key ] [ int ] NULL ) ON [ PRIMARY ]";
query = query.Replace(" . ", ".");
query = query.Replace("[ ", "[");
query = query.Replace(" ]", "]");
// Selects what is between parenthesizes 
String fieldsString = new String(query.SkipWhile(c => c != '(').TakeWhile(c => c != ')').ToArray());
// Selects the fields
String[] fields = fieldsString.Split(',').Select(line => new Regex("''[''w+'']").Match(line).Value).ToArray();
// Selects table name
String tableName = new Regex("''[''w+''](''.''[''w+''])*").Match(query).Value;

我希望它有所帮助。