If you use .NET, you can use server management objects:
var so = new ScriptingOptions(); so.Triggers = true; so.DriForeignKeys = true; so.DriDefaults = true; so.DriAllConstraints = true; so.DriAllKeys = true; so.DriIndexes = true; so.DriUniqueKeys = true; so.DriPrimaryKey = true; so.Indexes = true; so.Default = true; so.ClusteredIndexes = true; so.IncludeDatabaseContext = true; so.TargetServerVersion = SqlServerVersion.Version90; var server = new Server("ServerName"); var db = server.Databases["DatabaseName"]; var stringColl = db.Tables["Table"].Script(so);
You will need to replace the table names and related objects (e.g. FK_OldTableName_xxx with FK_NewTableName_xxx) in the generated script:
var sb = new StringBuilder(); foreach(var s in stringColl) { var r = s.Replace("OldTableName", "NewTableName"); sb.AppendLine(r); }
And then do:
db.Execute(sb.ToString());
Please note that this is pretty naive code: it will only work if the names of your constraints and keys match the format: FK_OldTableName_xxx / CK_OldTableName_xxx .. If they have other names, you need to strengthen the string replacement code, probably using Regexes for Search for T-SQL creation patterns (for example, CREATE INDEX, FOREIGN KEY .., etc.).
Ben m
source share