c# - 在不对数据库连接执行查询的情况下解析 SQL Server 查询

标签 c# sql-server

<分区>

这里有点难过。摆在我面前的任务是获取一个存储在字符串中的 SQL 查询(让我们假设它现在是一个有效的查询);将“选择列表”存储在字符串数组中,每个数组元素与一个选择列表项相关;最后将“from 子句”存储在它自己的字符串变量中。我觉得这个练习是我自己写一个 SQL 查询解析器,但我不知道 SQL Server 是如何解析查询的。非常感谢任何对资源有帮助的方向。

我已经能够使用蛮力方法解决问题,我执行以下操作:

1 - 通过启动一个循环来查找 from 子句,该循环查找单词“from”的后续实例,直到索引位置后面的所有内容都可以使用“select *”选择列表

private string GetFromClause(string selectstatement,string connectionString)
{
    string teststatement = selectstatement;
    int startindex = GetFirstFromIndex(teststatement);
    while (startindex != -1)
    { 
        teststatement=teststatement.Substring(startindex);
        if (DoesSelectWork(string.Format("select * {0}", teststatement)
                                                    , connectionString))
            return teststatement;
        else
            startindex = GetNextFromIndex(teststatement);

     }
    throw new ReportException("Could not find From Clause");
}

2- 从传递的查询中删除现在找到的“from 子句”;使用 .split(',') 将剩余的字符串放入数组中。现在遍历数组并使用找到的“from 子句”测试每个数组元素。如果测试通过,我们就有了一个有效的选择列表项;如果不是,我们想将这个元素与下一个数组元素组合,并继续这样做直到测试通过(处理强制转换语句等,这些语句会在选择列表语法中引入逗号)

private string[] GetSelectFields(string query, 
                                string fromclause,
                                string connectionString)
{
    int index = query.IndexOf(fromclause);
    string fromless = (index < 0)
        ? query
        : query.Remove(index, fromclause.Length);
    fromless = fromless.Substring(fromless.IndexOf("SELECT") + "SELECT".Length);
    List<string> finalselect = new List<string>();
    string[] selectFields = fromless.Split(',');
    index = 0;            
    string currentString = string.Empty;
    while (index<selectFields.Length)
    {
        currentString += selectFields[index];
        if (DoesSelectWork(string.Format("select {0} {1}"
                , currentString, fromclause), connectionString))
        {
            finalselect.Add(currentString);
            currentString = string.Empty;
        }
        else {
            currentString += ",";
        }
        index++;
    }
    return finalselect.ToArray();
}

最佳答案

作为一般规则,您不能使用简单的搜索方法来解析 SQL,规则太复杂了。你需要一个完整的词法分析器和语法。但自从 SQL Server 2012 以来,您就拥有了 Transact-SQL 语言服务选项,这是像 Visual Studio 这样的工具用来解析没有后端服务器的 T-SQL 的工具。您可以通过 C# 利用它 Microsoft.SqlServer.Management.SqlParser.Parser.Parse() .

关于c# - 在不对数据库连接执行查询的情况下解析 SQL Server 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26182859/

相关文章:

c# - c# - web api中 "$"关键字的用途是什么

c# - MVC3 阻止客户端设置模型值

c# - Blazor 数据列表 onchange 事件未触发

SQL Server 2008 : I/O Wait Time per Database File

sql - 为什么我的查询在获取偏移量较大的记录时速度很慢?

c# - 客户截断查询字符串,导致 FormatException

c# - Entity Framework 查找结果与 LINQ 结果

sql-server - WITH VIEW_METADATA 选项对 SQL Server 中的 View 有何作用?

c# - 使用 CLR 存储过程在事务内记录 TSQL

sql-server - Coldfusion 可以处理多少数据源