-->

Using SMO to get create script for table defaults

2019-05-08 16:08发布

问题:

I'm trying to create a database scripter tool for a local database I'm using.

I've been able to generate create scripts for the tables, primary keys, indexes, and foreign keys, but I can't find any way to generate create scripts for the table defaults.

For indexes, it's as easy as

foreach (Index index in table.Indexes)
{
    ScriptingOptions drop = new ScriptingOptions();
    drop.ScriptDrops = true;
    drop.IncludeIfNotExists = true;

    foreach (string dropstring in index.Script(drop))
    {
        createScript.Append(dropstring);
    }

    ScriptingOptions create = new ScriptingOptions();
    create.IncludeIfNotExists = true;

    foreach (string createstring in index.Script(create))
    {
        createScript.Append(createstring);
    }
}

But the Table object doesn't have a Defaults property. Is there some other way to generate scripts for the table defaults?

回答1:

Try using Scripter object with DriAll option set:

Server server = new Server(@".\SQLEXPRESS");
Database db = server.Databases["AdventureWorks"];
List<Urn> list = new List<Urn>();
DataTable dataTable = db.EnumObjects(DatabaseObjectTypes.Table);
foreach (DataRow row in dataTable.Rows)
{
   list.Add(new Urn((string)row["Urn"]));
}
Scripter scripter = new Scripter();
scripter.Server = server;
scripter.Options.IncludeHeaders = true;
scripter.Options.SchemaQualify = true;
scripter.Options.SchemaQualifyForeignKeysReferences = true;
scripter.Options.NoCollation = true;
scripter.Options.DriAllConstraints = true;
scripter.Options.DriAll = true;
scripter.Options.DriAllKeys = true;
scripter.Options.DriIndexes = true;
scripter.Options.ClusteredIndexes = true;
scripter.Options.NonClusteredIndexes = true;
scripter.Options.ToFileOnly = true;
scripter.Options.FileName = @"C:\tables.sql";
scripter.Script(list.ToArray());


回答2:

While I haven't used SMO, I looked up MSDN and here is what I found.

Table has a Columns property (column collection), which should have reference to each column.
Each Column will have a DefaultConstraint property.

Is this what you are looking for?



回答3:

Addition to the Pavel's answer.

I needed to get the script for a invidual table only. 1. I wanted to pass the table schema name and table name as parameter and generate script. 2. assign the script to a variable rather than writing to file.

code for a individual table:

/*get a particular table script only*/
Table myTable = db.Tables["TableName", "SchemaName"];
scripter.Script(new Urn[] { myTable.Urn});

Write script to a variable:

StringCollection sc = scripter.Script(new Urn[] { myTable.Urn });
foreach (string script in sc)
{
    sb.AppendLine();
    sb.AppendLine("--create table");
    sb.Append(script + ";");
}

I hope it will help future readers.