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