Skip to content

Instantly share code, notes, and snippets.

@keithbloom
Created February 8, 2011 10:41
Show Gist options
  • Save keithbloom/816251 to your computer and use it in GitHub Desktop.
Save keithbloom/816251 to your computer and use it in GitHub Desktop.
A powershell script which creates a couple of SQL files to drop and re-create foreign key constraints
#See http://msdn.microsoft.com/en-us/library/cc281962.aspx
PowerShell -NoExit -Command "$HOME\Documents\WindowsPowerShell\InitializeSQLProvider.ps1"
cd SQLSERVER:\sql\`(local`)\SQLSERVER2008\Databases\AdventureWorks2008\Tables
$opts = New-Object Microsoft.SqlServer.Management.Smo.ScriptingOptions
$opts.ScriptDrops = $true
$tables = ls | where {$_.Schema -eq "Production"}
$tables | foreach {$_.ForeignKeys} | foreach {$_.Script()} >> C:\Temp\CreateKeysScript.sql
$tables | foreach {$_.ForeignKeys} | foreach {$_.Script($opts)} >> C:\Temp\DropKeysScript.sql
@doerodney
Copy link

Thanks, this solved problem for me. One comment - you misspelled 'foreign' in a few places. Mark Twain said that he didn't give a damn for any man who could only spell a word one way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment