Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何提取SQL列和表信息_C#_Regex - Fatal编程技术网

C# 如何提取SQL列和表信息

C# 如何提取SQL列和表信息,c#,regex,C#,Regex,我知道这是一个非常古老和基本的问题,但在我的情况下,这是有点不同 问题:我有一个字符串,其中包含以下数据 select * from table1; select col1,col2,col5 from table2; select col8 from table3; 我需要从上面的字符串中找到列列表和使用的表名 我已经用.lastIndexOf()和.SubString()尝试过了,但它没有给出我想要的确切输出 所需输出: 表名称:“表2”使用的列:“col1、col2、col5” 表名称

我知道这是一个非常古老和基本的问题,但在我的情况下,这是有点不同

问题:我有一个字符串,其中包含以下数据

select * from table1; select col1,col2,col5 from table2; select col8 from table3;
我需要从上面的字符串中找到列列表和使用的表名

我已经用
.lastIndexOf()和.SubString()尝试过了,但它没有给出我想要的确切输出

所需输出:

  • 表名称:“表2”使用的列:“col1、col2、col5”
  • 表名称:“表1”使用的列:*“
  • 表名称:“表3”使用的列:“col8”
如何提取上述数据?

您可以使用以下代码:

    string storedProcContent = "select * from table1; select col1,col2,col5 from table2; select col8 from table3;";
    Regex rx = new Regex(@"select ([\w,\*]+?) from ([\w]+)", RegexOptions.IgnoreCase|RegexOptions.Compiled);
    MatchCollection matches = rx.Matches(storedProcContent);

    Console.WriteLine("{0} matches found in:\n   {1}",
                       matches.Count, storedProcContent);

    foreach (Match match in matches)
    {
        GroupCollection groups = match.Groups;
        Console.WriteLine("Table name = {0}", groups[2].Value);
        Console.WriteLine("Column Used = {0}", groups[1].Value);
    }
输出:

3 matches found in:
   select * from table1; select col1,col2,col5 from table2; select col8 from table3;
Table name = table1
Column Used = *
Table name = table2
Column Used = col1,col2,col5
Table name = table3
Column Used = col8

这不是一个基本问题:SQL语法很复杂,解析它也不容易。谷歌搜索“sql解析器”以了解更多信息。但我假设您只希望能够解析SQL语法的一个子集。在这种情况下,您需要定义要支持的子集和方言。仅仅能够解析一个示例字符串并没有多大用处。@joe说,我们可以让它在这个示例中工作,但是如果您使用一个CTE和1000个嵌套的sql语句进行连接,或者什么都没有,我认为没有人愿意为您使用该代码伤残他人负责使用
Split()
要将其分离为单独的语句,然后编写代码以解析出
选择
FROM
之间的部分,对于每个语句,再次在该部分上使用
拆分
,并检索列名列表。我们不会为您编写SQL解析器。