看看 SMO 的Scripter类。以下基本示例适用于我:
using System.Data.SqlClient;
using System.IO;
using System.Text;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
namespace SqlExporter
{
class Program
{
static void Main(string[] args)
{
var server = new Server(new ServerConnection {ConnectionString = new SqlConnectionStringBuilder {DataSource = @"LOCALHOST\SQLEXPRESS", IntegratedSecurity = true}.ToString()});
server.ConnectionContext.Connect();
var database = server.Databases["MyDatabase"];
var output = new StringBuilder();
foreach (Table table in database.Tables)
{
var scripter = new Scripter(server) {Options = {ScriptData = true}};
var script = scripter.EnumScript(new SqlSmoObject[] {table});
foreach (var line in script)
output.AppendLine(line);
}
File.WriteAllText(@"D:\MyDatabase.sql", output.ToString());
}
}
}
注意:此示例不处理任何外键约束或表之间的其他依赖关系。
参考:
- 这个 SO 问题(这让我进入了Scripter课程)
- 这个 MSDN 论坛问题(解释了如何使用EnumScript方法)