i have generated scripts manually through Generate script in tasks menu by right clicking database.
Now my problem
Hopefully a it would guide you and upcoming ones.
You have to add following four references to your project to include following required namespaces
To add a references
Reference Microsoft.SqlServer.Smo.dll
namespaces
using System.Data.SqlClient;
using System.Collections.Specialized;
using Microsoft.SqlServer.Management.Smo;
Now use following code in any function or button click event
// For Me Server is ".\SQLExpress" You may have changed
Server myServer = new Server(@".\SQLExpress");
Scripter scripter = new Scripter(myServer);
//Databas1 is your database Name Thats Changable
Database myAdventureWorks = myServer.Databases["Database1"];
/* With ScriptingOptions you can specify different scripting
* options, for example to include IF NOT EXISTS, DROP
* statements, output location etc*/
ScriptingOptions scriptOptions = new ScriptingOptions();
scriptOptions.ScriptDrops = true;
scriptOptions.IncludeIfNotExists = true;
string scrs = "";
string tbScr = "";
foreach (Table myTable in myAdventureWorks.Tables)
{
/* Generating IF EXISTS and DROP command for tables */
StringCollection tableScripts = myTable.Script(scriptOptions);
foreach (string script in tableScripts)
scrs += script;
/* Generating CREATE TABLE command */
tableScripts = myTable.Script();
foreach (string script in tableScripts)
tbScr += script;
}
// For WinForms
MessageBox.Show(scrs + "\n\n" + tbScr);
//For Console
//Console.WriteLine(scrs + "\n\n" + tbScr);
It involved http://www.mssqltips.com/sqlservertip/1833/generate-scripts-for-database-objects-with-smo-for-sql-server/ Answer (above) by David Brabant and the SO link above
Code Block 2 is used. Now you can use others as well
i could not find myserver there but it is resolved as well in above code.