简体   繁体   English

如何使用正则表达式选择SQL的列名和表?

[英]How to select column names and tables of an SQL using regex?

I have an SQL string that looks something like this: 我有一个看起来像这样的SQL字符串:

SELECT
    USER."ID", USER."NAME", USER."BIRTH",USER."GENDER",
    PACKAGE."type"
    PACKAGE."code"
FROM
    "DBNAME"."USER" USER,
    "DBNAME2"."PACKAGE" PACKAGE
WHERE
    USER."PACKAGE_ID" = PACKAGE."ID"
ORDER BY
    USER."NAME";

How should I write my regular expression in C# to extract all the column names between the SELECT and FROM keywords, and then the table names in the FROM clause? 我应该如何在C#中编写正则表达式以提取SELECT和FROM关键字之间的所有列名称,然后提取FROM子句中的表名称?

The expected output should find these so that I can put them into List to loop through: 预期的输出应该找到这些,以便我可以将它们放入List以遍历:

ColumnsList: ColumnsList:

USER."ID"
USER."NAME"
USER."BIRTH"
USER."GENDER"
PACKAGE."type"
PACKAGE."code"

TablesList: TablesList:

"DBNAME"."USER" USER
"DBNAME2"."PACKAGE" PACKAGE

Use this Regex will get the column and table name: 使用此正则表达式将获取列和表的名称:

  (?is)SELECT(.*?)(?<!\w*")FROM(?!\w*?")(.*?)(?=WHERE|ORDER|$)
  • Group[1] : column 组[1]:列
  • Group[2] : table name 组[2]:表名

Code Samples: 代码样例:

string sql=@"SELECT
    USER.""ID"", USER.""NAME"", USER.""BIRTH"",USER.""GENDER"",
    PACKAGE.""type""
    PACKAGE.""code""
FROM
    ""DBNAME"".""USER"" USER,
    ""DBNAME2"".""PACKAGE"" PACKAGE
WHERE
    USER.""PACKAGE_ID"" = PACKAGE.""ID""
ORDER BY
    USER.""NAME"";";

    var reg=new Regex(@"(?is)SELECT(.*?)(?<!\w*"")FROM(?!\w*?"")(.*?)(?=WHERE|ORDER|$)");
    var colunms=reg.Match(sql).Groups[1].Value.Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries);
    var tables=reg.Match(sql).Groups[2].Value.Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Lambda表达式选择列名称? - How to select column names using a lambda expression? LINQ to SQL:如何在连接表时处理不明确的列名? - LINQ to SQL: How to handle ambiguous column names when joining tables? 如何为表名称解析SQL查询语句 - How to parse a SQL Query statement for the names of the tables 将包含所有表和列名的 SQL 语句添加到字典中 - Adding SQL Statement with all tables and column names into a Dictionary 使用实体框架,如何创建查询以从数据库中获取所有表的列名 - Using Entity Framework, how to create a query which will fetch the column names of all tables from a database 连接3个表并使用linq选择1列 - Join 3 tables and select 1 column using linq 如何在VB.NET中使用SQL从特定数据库中检索Ms访问表名称 - How to retrieve Ms access tables names from specific database using SQL in VB.NET 在C#中使用OleDbCommandBuilder更新列名称包含@符号的表 - Updating tables with column names containing @ symbols using OleDbCommandBuilder in C# 如何从SQL数据库返回列名 - How to return column names from SQL database 如何在没有列名的情况下序列化sql数据? - How to serialize sql data without the column names?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM