11

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.]

2

4 Answers 4

11

The following code will create a script at location "QQQ" by specifying the server "XXX", table "ZZZ" and schema "PPP". There are a few example scripts floating out there to do copies of entire databases, this is for just tables. This is what I was trying to figure out this whole time and I finally got it working using the code below. This is meant to be a simple example, the resulting scripts for instance don't create the indexes of a table, just its most basic structure. To specify how the script is created, pass an instance of ScriptingOptions into the call to table.Script().

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

namespace SmoTest {
    class Program {
        static void Main(string[] args) {

            Server server = new Server("XXX");
            Database database = new Database();
            database = server.Databases["YYY"];
            Table table = database.Tables["ZZZ", @"PPP"];

            StringCollection result = table.Script();

            var script = "";
            foreach (var line in result) {
                script += line;
            }

            System.IO.StreamWriter fs = System.IO.File.CreateText(@"QQQ");
            fs.Write(script);
            fs.Close();

        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

6

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();
        }
    }
}

2 Comments

Do you have any insights on the ScriptingOptions class? How, for instance, can I guarantee I get an exact copy of my existing table (including all properties like indexes or whatever)? There are so many properties to set here, I don't know which ones to set and which ones to leave alone.
@sooprise I'm not sure, I probably would have opted for PowerShell in this case. You can go through the options listed here and see which ones might apply to your tables.
0

You can try below functions to get table script from SQL Server Database using C#. Complete Article: Transfer data or script between two SQL Server databases

C# Code:

public string GetTableScript(string TableName, string ConnectionString)
{
    string Script = "";

    string Sql = "declare @table varchar(100)" + Environment.NewLine +
    "set @table = '" + TableName + "' " + Environment.NewLine +
        //"-- set table name here" +
    "declare @sql table(s varchar(1000), id int identity)" + Environment.NewLine +
    " " + Environment.NewLine +
        //"-- create statement" +
    "insert into  @sql(s) values ('create table [' + @table + '] (')" + Environment.NewLine +
    " " + Environment.NewLine +
        //"-- column list" +
    "insert into @sql(s)" + Environment.NewLine +
    "select " + Environment.NewLine +
    "    '  ['+column_name+'] ' + " + Environment.NewLine +
    "    data_type + coalesce('('+cast(character_maximum_length as varchar)+')','') + 
    ' ' +" + Environment.NewLine +
    "    case when exists ( " + Environment.NewLine +
    "        select id from syscolumns" + Environment.NewLine +
    "        where object_name(id)=@table" + Environment.NewLine +
    "        and name=column_name" + Environment.NewLine +
    "        and columnproperty(id,name,'IsIdentity') = 1 " + Environment.NewLine +
    "    ) then" + Environment.NewLine +
    "        'IDENTITY(' + " + Environment.NewLine +
    "        cast(ident_seed(@table) as varchar) + ',' + " + Environment.NewLine +
    "        cast(ident_incr(@table) as varchar) + ')'" + Environment.NewLine +
    "    else ''" + Environment.NewLine +
    "   end + ' ' +" + Environment.NewLine +
    "    ( case when IS_NULLABLE = 'No' then 'NOT ' else '' end ) + 'NULL ' + " + Environment.NewLine +
    "    coalesce('DEFAULT '+COLUMN_DEFAULT,'') + ','" + Environment.NewLine +
    " " + Environment.NewLine +
    " from information_schema.columns where table_name = @table" + Environment.NewLine +
    " order by ordinal_position" + Environment.NewLine +
    " " + Environment.NewLine +
        //"-- primary key" +
    "declare @pkname varchar(100)" + Environment.NewLine +
    "select @pkname = constraint_name from information_schema.table_constraints" + Environment.NewLine +
    "where table_name = @table and constraint_type='PRIMARY KEY'" + Environment.NewLine +
    " " + Environment.NewLine +
    "if ( @pkname is not null ) begin" + Environment.NewLine +
    "    insert into @sql(s) values('  PRIMARY KEY (')" + Environment.NewLine +
    "    insert into @sql(s)" + Environment.NewLine +
    "        select '   ['+COLUMN_NAME+'],' from information_schema.key_column_usage" + Environment.NewLine +
    "        where constraint_name = @pkname" + Environment.NewLine +
    "        order by ordinal_position" + Environment.NewLine +
        //"    -- remove trailing comma" +
    "    update @sql set s=left(s,len(s)-1) where id=@@identity" + Environment.NewLine +
    "    insert into @sql(s) values ('  )')" + Environment.NewLine +
    "end" + Environment.NewLine +
    "else begin" + Environment.NewLine +
        //"    -- remove trailing comma" +
    "    update @sql set s=left(s,len(s)-1) where id=@@identity" + Environment.NewLine +
    "end" + Environment.NewLine +
    " " + Environment.NewLine +
    "-- closing bracket" + Environment.NewLine +
    "insert into @sql(s) values( ')' )" + Environment.NewLine +
    " " + Environment.NewLine +
        //"-- result!" +
    "select s from @sql order by id";

    DataTable dt = GetTableData(Sql, ConnectionString);
    foreach (DataRow row in dt.Rows)
    {
        Script += row[0].ToString() + Environment.NewLine;
    }

    return Script;
}




public DataTable GetTableData(string Sql, string ConnectionString)
{
    SqlConnection con = new SqlConnection(ConnectionString);
    try
    {
        con.Open();
        SqlCommand selectCommand = new SqlCommand(Sql, con);
        DataSet dataSet = new DataSet();
        new SqlDataAdapter(selectCommand).Fill(dataSet);
        DataTable table = dataSet.Tables[0];
        return table;
    }
    catch (Exception)
    {
        return new DataTable();
    }
    finally
    {
        con.Close();
    }
}

Comments

0

Table Script

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using Microsoft.SqlServer.Management.Smo; 
using Microsoft.SqlServer.Management.Sdk.Sfc; 
using Microsoft.SqlServer.Management.Common; 
using System.Collections.Specialized; 
using System.IO; 
using System.Data; 
using Microsoft.SqlServer.Management; 
using System.Data.SqlClient;

namespace GenrateScriptsForDatabase
{
    class Program
    {
        static void Main(string[] args)
        {

            var server = new Server(new ServerConnection { ConnectionString = new SqlConnectionStringBuilder { DataSource = @"Your Server Name", UserID="Your User Id",Password="Your Password" }.ToString() });
            server.ConnectionContext.Connect();
            var database = server.Databases["Your Database Name"];

            using (FileStream fs = new FileStream(@"H:\database_scripts\Gaurav.sql", FileMode.Append, FileAccess.Write))
            using (StreamWriter sw = new StreamWriter(fs))
            {
                for each (Table table in database.Tables)
                {
                    if (table.Name == "Your Table Name")
                    {
                        var scripter = new Scripter(server) { Options = { ScriptData = true } };
                        var script = scripter.EnumScript(new SqlSmoObject[] { table });
                        for each (string line in script)
                        {

                                sw.WriteLine(line);
                                Console.WriteLine(line);
                            }
                        }
                    }
                }
            }
        }
}

2 Comments

namespace are: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.SqlServer.Management.Smo; using Microsoft.SqlServer.Management.Sdk.Sfc; using Microsoft.SqlServer.Management.Common; using System.Collections.Specialized; using System.IO; using System.Data; using Microsoft.SqlServer.Management; using System.Data.SqlClient;
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.

Your Answer

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.