Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I generate CREATE TABLE script from code?

In SQL Server Management Studio, I can generate the CREATE TABLE script for a table by right-clicking a table and choosing Script Table As.

How can I get this same result in C#? Can I utilize SMO or some other methodology?

[To avoid the question getting closed, please post working code samples, not one-liners or links to the high-level documentation.]

like image 253
sooprise Avatar asked Jul 25 '12 18:07

sooprise


People also ask

How do you generate create table script for all tables in SQL Server database?

Right click on the DB_NAME -> Select Task -> Select Generate Script. Follow along the presented wizard and select all tables in that database to generate the scripts.


1 Answers

Here's a slightly more complete example (stolen from my buddy Ben Miller):

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Smo.SqlEnum;
using Microsoft.SqlServer.Management.Smo.CoreEnum;
using System.Configuration;
using System.Collections.Specialized;

namespace SmoTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Server srv = new Server();

            // really you would get these from config or elsewhere:
            srv.ConnectionContext.Login = "foo";
            srv.ConnectionContext.Password = "bar";
            srv.ConnectionContext.ServerInstance = "ServerName";
            string dbName = "DatabaseName";

            Database db = new Database();
            db = srv.Databases[dbName];

            StringBuilder sb = new StringBuilder();

            foreach(Table tbl in db.Tables)
            {
                ScriptingOptions options = new ScriptingOptions();
                options.ClusteredIndexes = true;
                options.Default = true;
                options.DriAll = true;
                options.Indexes = true;
                options.IncludeHeaders = true;

                StringCollection coll = tbl.Script(options);
                foreach (string str in coll)
                {
                    sb.Append(str);
                    sb.Append(Environment.NewLine);
                }
            }
            System.IO.StreamWriter fs = System.IO.File.CreateText("c:\\temp\\output.txt");
            fs.Write(sb.ToString());
            fs.Close();
        }
    }
}
like image 96
Aaron Bertrand Avatar answered Sep 17 '22 16:09

Aaron Bertrand