我使用以下代码获取查询中的语句列表:
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";
如果查询错误,如何获取语句列表?
谢谢!