我在 GAC 中找到了程序集 Microsoft.SqlServer.BatchParser 以及它的朋友 Microsoft.SqlServer.BatchParserClient,其中包含接口 IBatchSource 的实现。
namespace Microsoft.SqlServer.Management.Common
{
internal class BatchSourceFile : IBatchSource
internal class BatchSourceString : IBatchSource
}
然后发生了以下对话。
大会:您好!我的名字是
Microsoft.SqlServer.Management.Common.ExecuteBatch。您想 StringCollection GetStatements(string sqlCommand) 吗?
我:是的,我愿意,BatchParserClient 程序集。谢谢提问!
可重复的说明(在家试试这个!)
- 安装Microsoft SQL Server 2008 R2 共享管理对象
- 将 Microsoft.SqlServer.BatchParser.dll 和 Microsoft.SqlServer.BatchParserClient.dll 从 GAC 复制到解决方案中的文件夹。
- 参考 Microsoft.SqlServer.BatchParser & Microsoft.SqlServer.BatchParserClient
程序.cs
using System;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using Microsoft.SqlServer.Management.Common;
namespace ScriptParser
{
class Program
{
static void Main(string[] args)
{
ExecuteBatch batcher = new ExecuteBatch();
string text = File.ReadAllText(@"Path_To_My_Long_Sql_File.sql");
StringCollection statements = batcher.GetStatements(text);
foreach (string statement in statements)
{
Console.WriteLine(statement);
}
}
}
}
应用程序配置
<?xml version="1.0"?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
</configuration>
另一种选择是使用此答案中描述的 ScriptDom:https ://stackoverflow.com/a/32529415/26877 。
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.SqlServer.TransactSql.ScriptDom;
namespace ScriptDomDemo
{
class Program
{
static void Main(string[] args)
{
TSql120Parser parser = new TSql120Parser(false);
IList<ParseError> errors;
using (StringReader sr = new StringReader(@"create table t1 (c1 int primary key)
GO
create table t2 (c1 int primary key)"))
{
TSqlFragment fragment = parser.Parse(sr, out errors);
IEnumerable<string> batches = GetBatches(fragment);
foreach (var batch in batches)
{
Console.WriteLine(batch);
}
}
}
private static IEnumerable<string> GetBatches(TSqlFragment fragment)
{
Sql120ScriptGenerator sg = new Sql120ScriptGenerator();
TSqlScript script = fragment as TSqlScript;
if (script != null)
{
foreach (var batch in script.Batches)
{
yield return ScriptFragment(sg, batch);
}
}
else
{
// TSqlFragment is a TSqlBatch or a TSqlStatement
yield return ScriptFragment(sg, fragment);
}
}
private static string ScriptFragment(SqlScriptGenerator sg, TSqlFragment fragment)
{
string resultString;
sg.GenerateScript(fragment, out resultString);
return resultString;
}
}
}