public static string ScriptTable(string connectionString, string schemaName, string tableName) { var builder = new System.Data.SqlClient.SqlConnectionStringBuilder(connectionString); //System.Console.WriteLine("Host: {0}", builder.DataSource); //System.Console.WriteLine("Data: {0}", builder.InitialCatalog); //System.Console.WriteLine("ISec: {0}", builder.IntegratedSecurity); //System.Console.WriteLine("User: {0}", builder.UserID); //System.Console.WriteLine("Pass: {0}", builder.Password); var conn = new System.Data.SqlClient.SqlConnection(connectionString); var sc = new Microsoft.SqlServer.Management.Common.ServerConnection(conn); var server = new Microsoft.SqlServer.Management.Smo.Server(sc); //server.ConnectionContext.Connect(); // Getting version automatically connects. //System.Console.WriteLine("Server Version: {0}", server.Information.Version); var sb = new StringBuilder(""); var database = server.Databases[builder.InitialCatalog]; var table = database.Tables[tableName, schemaName]; // Script DROP. var options = new Microsoft.SqlServer.Management.Smo.ScriptingOptions(); // If IncludeIfNotExists = true then procedure text will be generated // through "EXEC dbo.sp_executesql @statement = N'". options.IncludeIfNotExists = true; options.ScriptDrops = true; var strings = table.Script(options); foreach (var s in strings) { sb.AppendLine(s); } sb.AppendLine(); // Script CREATE. options = new Microsoft.SqlServer.Management.Smo.ScriptingOptions(); //options.AppendToFile = true; options.ClusteredIndexes = true; options.NoCollation = true; //options.DriClustered = false; //options.NonClusteredIndexes = true; //options.DriNonClustered = false; //options.Indexes = true; //options.DriIndexes = false; //options.FileName = fileInfo.FullName; //options.Permissions = true; strings = table.Script(options); foreach (var s in strings) { sb.AppendLine(s); } return(sb.ToString()); }
public override StringCollection Script(SmoScriptingContext context) { var scripter = new Microsoft.SqlServer.Management.Smo.Scripter(context.Server); Microsoft.SqlServer.Management.Smo.ScriptingOptions options = scripter.Options; options.IncludeDatabaseContext = context.ScriptDatabaseContext; StringCollection scriptingResult = scripter.Script(new[] { ScriptedObject }); var result = new StringCollection(); foreach (string scriptedBatch in scriptingResult) { result.Add(scriptedBatch); AddLineEnding(result); AddLineEnding(result); } return(result); }