Hi,I use the below script to script out FKs in a database:#DECLARE TIMESTAMP FOR THE FILES$timestamp = Get-Date -Format yyyy-MM-dd#SCRIPTSL SQLSERVER:\SQL\'MyServer'\DEFAULT\Databases\'MyDB'\Tables$so = new-object Microsoft.SqlServer.Management.Smo.ScriptingOptions$so.IncludeIfNotExists = 1$so.SchemaQualify = 1$so.SchemaQualifyForeignKeysReferences = 1$so.ScriptSchema = 1dir | foreach {$_.ForeignKeys} | foreach {$_.Script()} > "Z:\MyDB\03_FKs $timestamp .sql"The result I get looks like this:ALTER TABLE [MySchema].[MyTable1] WITH CHECK ADD CONSTRAINT [FK_MyTable1_MyTable2_ID] FOREIGN KEY([ID])REFERENCES [MyTable2] ([ID])ON DELETE CASCADEI am getting an error when using the above script:Msg 1767, Level 16, State 0, Line 1Foreign key 'FK_MyTable1_MyTable2_ID' references invalid table 'MyTable2'.Msg 1750, Level 16, State 0, Line 1Could not create constraint. See previous errors. The reason for this is because MyTable2 belongs to a schema other then 'dbo', so the generated script should look like this:ALTER TABLE [MySchema].[MyTable1] WITH CHECK ADD CONSTRAINT [FK_MyTable1_MyTable2_ID] FOREIGN KEY([ID])REFERENCES [b][MySchema].[/b][MyTable2] ([ID])ON DELETE CASCADEAny ideas?Thanks. Quick Reply
↧