1

我使用以下代码获取查询中的语句列表:

using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using Microsoft.SqlServer.TransactSql.ScriptDom;

namespace SqlTokenazer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Tokenaze();
        }

        private void Tokenaze()
        {
            rtbLog.Clear();

            string script = "select * from dbo.Mytable where columnName = 0 delete from dbo.Mytable where columnName = 0";
            var sqlScript = ParseScript(script);

            PrintStatements(sqlScript);
        }

        public TSqlScript ParseScript(string script){
            IList<ParseError> parseErrors;
            TSql100Parser tsqlParser = new TSql100Parser(true);
            TSqlFragment fragment;
            using (StringReader stringReader = new StringReader(script))
            {
                fragment = (TSqlFragment)tsqlParser.Parse(stringReader, out parseErrors);
            }
            if (parseErrors.Count > 0)
            {
                var retMessage = string.Empty;
                foreach (var error in parseErrors)
                {
                    retMessage += error.Number + " - " + error.Message + " - position: " + error.Offset + ";\r\n";
                }
                rtbLog.Text += retMessage;
            }
            return (TSqlScript)fragment;

        }

        public void PrintStatements(TSqlScript tsqlScript)
        {

            if (tsqlScript != null)
            {
                foreach (TSqlBatch batch in tsqlScript.Batches)
                {
                    if (batch.Statements.Count == 0) continue;

                    foreach (TSqlStatement statement in batch.Statements)
                    {
                        rtbLog.Text += string.Format("{0}\r\n", statement.GetType().ToString());
                    }
                }

            }
        }
    }

}

结果:

Microsoft.SqlServer.TransactSql.ScriptDom.SelectStatement
Microsoft.SqlServer.TransactSql.ScriptDom.DeleteStatement

但是当我在查询中出错时,语句列表是空的:(

string script = "select * from dbo.Mytable where ... delete from dbo.Mytable where columnName = 0";

如果查询错误,如何获取语句列表?

谢谢!

4

1 回答 1

1

我知道这是一个老问题,但我在谷歌搜索时遇到了它,所以我想我会回答它。

如果您的问题是,如果无法解析 SQL,如何获取语句列表,简短的回答是您不能 - 解析器不知道语句列表是什么。您必须查看错误并弄清楚。

如果您的问题是,输入代码有什么问题,那就是 select 和 delete 语句都在同一行。如果你用分号分隔它们或将它们分成两行,它会起作用,你可以得到你的两个语句。

于 2018-03-28T19:30:28.040 回答