Question

I have a database with 300 tables. I need to clean the tables, so I have written a script which drops all of the constraints, triggers, primary keys, and foreign keys.

I have managed to create scripts using the generate scripts feature, but they only include primary keys inside the CREATE statements.

I need to get them as ALTER TABLE statements so that I can drop the keys, clear database, insert new data, and restore all the keys, constraints, etc.

Was it helpful?

Solution

Powershell and SMO are going to be your friends here:

$option_drop = new-object Microsoft.SqlServer.Management.Smo.ScriptingOptions;
$option_drop.ScriptDrops = $true;

"" > drop_primary_keys.sql
"" > create_primary_keys.sql

$server = new-object Microsoft.SqlServer.Management.Smo.Server ".";
$db = $server.Databases['AdventureWorks'];
foreach ($table in $db.Tables) {
    foreach ($index in $table.Indexes) {
        if ($index.IndexKeyType -eq "DriPrimaryKey") {
            $index.Script( $option_drop ) >> drop_primary_keys.sql
            $index.Script() >> create_primary_keys.sql
        }
    }
}

A couple of notes here:

  • Running this script will nuke any existing files of the name "drop_primary_keys.sql" and "create_primary_keys.sql", so proceed with caution
  • The script doesn't take into account any foreign keys since you said you already have a way to do that.
  • You may have to tweak the ScriptingOptions object to fit your needs. Specifically, I'm using the defaults on the create, so you may need to create another ScriptingOptions object and set whichever options you think appropriate.

Other than that, good hunting.

OTHER TIPS

Msdn has an article about disabling/enabling triggers and foreign keys:

http://msdn.microsoft.com/en-us/magazine/cc163442.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top