I googled and I found this issue on Github which has some interesting discussion: https://github.com/microsoft/sqlmanagementobjects/issues/11. There are also some alternative suggested.
I don't work with SMO myself.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I have been looking into using SMO into trying to create, alter and drop tables/views/stored procedures using a similar structure to the code below:
if (taskType == TaskType.Alter.ToString())
{
if (item.SourceResults != null && item.SourceResults != "" && item.SelectionCheckboxProperty == true && item.DatabasePropertyType == DatabasePropertyType.Table)
{
sourceConnectionstring = $"server={sourceservername};Database={sourcedatabase};User Id={sourceusername};Password={sourcepassword};Encrypt=False;Persist Security Info=True;Integrated Security=False;";
using (SqlConnection sourceConnection = new SqlConnection(sourceConnectionstring))
{
await sourceConnection.OpenAsync();
Server sourceserver = new Server(sourceservername);
Database sourceDataBase = sourceserver.Databases[sourcedatabase];
Table sourceTable = sourceDatabase.Tables[item.SourceResults];
Scripter scripter = new Scripter(sourceserver);
scripter.Options.ScriptDrops = true;
scripter.Options.ScriptForCreateOrAlter = true;
scripter.Options.ScriptForAlter = false;
scripter.Options.ScriptSchema = true;
scripter.Options.ScriptData = false;
Urn tableUrn = sourceTable.Urn;
try
{
ScriptDatalabel.Visibility = Visibility.Visible;
StringCollection createScript = scripter.Script(new Urn[] { tableUrn });
StringBuilder sb = new StringBuilder();
However, I have been struggling to get 'ALTER' to any table/stored procedure/view as I keep on getting 'CREATE' all the time when I use debug in visual in createScript
.
I have created the code above and results were always create instead of alter when the source and target were identical. (e.g., if the table were identical but the target is missing like one or more columns, it will always do create instead of alter).
Edit 1:
I have tried changing the options into
scripter.Options.ScriptDrops = false;
//scripter.Options.ScriptForCreateOrAlter = true;
scripter.Options.ScriptForAlter = true;
scripter.Options.ScriptSchema = true;
scripter.Options.ScriptData = false;
However, my createScript
is always showing the following:
that is the only item in the array list. For altering, what would be the best approach for getting alter script? What options should I be using?
Edit 2:
I have a few extra questions:
I googled and I found this issue on Github which has some interesting discussion: https://github.com/microsoft/sqlmanagementobjects/issues/11. There are also some alternative suggested.
I don't work with SMO myself.