Search code examples
c#.netsql-serversmo

Get Sql server's data using smo


I'm using Sql Server Smo to create the scheme of database by C# application. However, I need a bit more, I also need to get data from each table as a script like below:

--........................................
INSERT INTO Table123 (...) VALUES (....)
INSERT INTO Table456 (...) VALUES (....)
--........................................

How can I do that and is it possible? Notice please that I need to create exactly a script using smo and not *.bak of a database, etc.


Solution

  • Have a look at SMO's Scripter class. The following basic sample works for me:

    using System.Data.SqlClient;
    using System.IO;
    using System.Text;
    using Microsoft.SqlServer.Management.Common;
    using Microsoft.SqlServer.Management.Smo;
    
    namespace SqlExporter
    {
    class Program
    {
    static void Main(string[] args)
    {
        var server = new Server(new ServerConnection {ConnectionString = new SqlConnectionStringBuilder {DataSource = @"LOCALHOST\SQLEXPRESS", IntegratedSecurity = true}.ToString()});
        server.ConnectionContext.Connect();
        var database = server.Databases["MyDatabase"];
        var output = new StringBuilder();
    
        foreach (Table table in database.Tables)
        {
            var scripter = new Scripter(server) {Options = {ScriptData = true}};
            var script = scripter.EnumScript(new SqlSmoObject[] {table});
            foreach (var line in script)
                output.AppendLine(line);
        }
        File.WriteAllText(@"D:\MyDatabase.sql", output.ToString());
    }
    }
    }
    

    Note: This example doesn't handle any foreign key constraints or other dependencies between tables.

    References:

    1. This SO question (that turned me onto the Scripter class)
    2. This MSDN forum question (that explained how to use the EnumScript method)