我正在使用Smo创建现有数据库的SQL脚本。为了进行测试,我删除了数据库并将脚本复制到新的查询中以再次创建它。不幸的是,此过程会产生错误。
'CREATE VIEW' must be the first statement in a query batch
由于我正在创建多个视图,因此该错误在SQL Server Management Studio的“消息”选项卡中多次显示。当我寻找解决方案时,我发现“创建视图”之前的关键字“转到”显然丢失了。类“ ScriptingOptions”中是否包含一个选项,以在生成的脚本中附加“ GO”?
代码:
public void GenerateSQLScripts(string dbName)
{
StringBuilder sb = new StringBuilder();
Server server = new Server(SqlServer);
Database db = server.Databases[dbName];
var scriptopt = new ScriptingOptions();
scriptopt.TargetServerVersion = SqlServerVersion.Version105; // Windows 2008 R2
scriptopt.AnsiPadding = true;
scriptopt.WithDependencies = true;
scriptopt.IncludeHeaders = true;
scriptopt.SchemaQualify = true;
scriptopt.ExtendedProperties = true;
scriptopt.TargetDatabaseEngineType = DatabaseEngineType.Standalone;
scriptopt.IncludeDatabaseContext = true;
scriptopt.ScriptDrops = false;
scriptopt.ScriptData = false;
scriptopt.ScriptSchema = true;
scriptopt.DriAllConstraints = true;
scriptopt.DriForeignKeys = true;
scriptopt.Indexes = true;
scriptopt.DriPrimaryKey = true;
scriptopt.DriUniqueKeys = true;
scriptopt.DriChecks = true;
scriptopt.AllowSystemObjects = false;
scriptopt.AppendToFile = false;
// script Tables
foreach (Table t in db.Tables)
{
if (!t.IsSystemObject)
{
StringCollection sc = t.Script(scriptopt);
foreach (string s in sc)
{
sb.AppendLine(s);
}
}
}
//Script Stored Procedures
foreach (StoredProcedure sp in db.StoredProcedures)
{
if (!sp.IsSystemObject)
{
var sc = sp.Script(scriptopt);
foreach (string s in sc)
{
sb.AppendLine(s);
}
}
}
//Views
foreach(View v in db.Views){
if (!v.IsSystemObject)
{
StringCollection sc = v.Script(scriptopt);
foreach (string s in sc)
{
sb.AppendLine(s);
}
}
}
File.WriteAllText(Path, sb.ToString());
}
您要查找的属性称为“ NoCommandTerminator”。将其设置为false,您应该会很好。我通过反复试验发现了这一点。实际上,我也正在使用SMO,并且正在将ScriptingOptions序列化为XML文件,以便以后可以对其进行更改。在我的配置中,我还说了帮助,如何配置它,这一行是我为添加GO语句编写的:假