tags:

views:

2473

answers:

2

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?

A: 

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?

shahkalpesh
+1  A: 

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());
Pavel Chuchuva