1

In SSMS, we can right click a database/table/index/... and select the "Script As" option to generate a drop and create script.

Is there a way to automate this script generation and drop the scripts to a temp location, rather than manually right clicking each object and generating them?

Aaron Bertrand
182k28 gold badges406 silver badges625 bronze badges
asked May 1, 2013 at 21:59
1

2 Answers 2

1

SQL Server Management Objects SMO is your answer. You can use it to accomplish this task. Here is an example to generate Create Table Scripts.

 public string GetTableDescription(string pDatabaseName, string pSchemaName, string pTableName, string connectionString)
 {
 connectionString = ConnectionHelper.RemoveProviderFromConnectionString(connectionString);
 Server server = new Server(new ServerConnection(new SqlConnection(connectionString)));
 Database db = server.Databases[pDatabaseName];
 Table t = db.Tables[pTableName, pSchemaName];
 ScriptingOptions baseOptions = new ScriptingOptions();
 baseOptions.NoCollation = true;
 baseOptions.SchemaQualify = true;
 baseOptions.DriDefaults = true;
 baseOptions.IncludeHeaders = false;
 baseOptions.DriPrimaryKey = true;
 baseOptions.ExtendedProperties = true;
 //baseOptions.DriAll = true;
 //baseOptions.Indexes = true;
 //baseOptions.DriAllKeys = true;
 //baseOptions.SchemaQualifyForeignKeysReferences = true;
 baseOptions.EnforceScriptingOptions = true;
 StringCollection result = t.Script(baseOptions);
 return StringCreate(result);
 }
answered May 1, 2013 at 22:50
1

You can use Powershell and SMO to do this - simple, efficient and customizable. Such script to script out database objects can be found here and here

answered May 1, 2013 at 23:31
2
  • Thanks Kin! The first link did the trick. Is there a way we can automate and rename the table names in the output file. Lets say, the script generate create index commands for Table_A, I need to the keyword Table_A within the output file to Table_B, so that i can run the create scripts against table_B Commented May 2, 2013 at 17:56
  • You can do a search+replace or use RegEx or generate the scripts with Powershell but just append _New to the script. Many ways to do it. Commented May 2, 2013 at 18:49

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.