I'm generating sql database script using c# code.
following code works fine for create table
but when I try to use scriptOptions.ScriptData = true;
it is throwing following exception.
An unhandled exception of type 'Microsoft.SqlServer.Management.Smo.FailedOperationException' occurred in Microsoft.SqlServer.Smo.dll
Additional information: This method does not support scripting data.
code
public static string ScriptDatabase(string dbConnectionString, string databaseName)
{
SqlConnection conn = new SqlConnection(dbConnectionString);
ServerConnection serverConn = new ServerConnection(conn);
var server = new Server(serverConn);
var database = server.Databases[databaseName];
var scripter = new Scripter(server);
// I tried this code also
// scripter.Options.ScriptData = true;
ScriptingOptions scriptOptions = new ScriptingOptions();
scriptOptions.ScriptDrops = false;
scriptOptions.ScriptData = true;
scriptOptions.ScriptSchema = true;
scriptOptions.IncludeIfNotExists = true;
string scrs = "";
string tbScr = "";
foreach (Table myTable in database.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 + "
";
}
return (scrs + "
" + tbScr);
}
See Question&Answers more detail:os