Generating sql code programmatically

前端 未结 5 1932
清酒与你
清酒与你 2020-12-03 02:28

i have generated scripts manually through Generate script in tasks menu by right clicking database.

Now my problem

5条回答
  •  情歌与酒
    2020-12-03 02:55

    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

    1. Right click your project in solution explorer and choose add reference
    2. Click Browse from upper menu
    3. And choose 4 dll files as instructed below

    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.

提交回复
热议问题