Welcome to Day 15 of my “A Month of PowerShell” series. This series will use the series landing page on this blog at http://blog.waynesheffield.com/wayne/a-month-of-powershell/. Please refer to this page to see all of the posts in this series, and to quickly go to them.

Adding a foreign key constraint to a table

Continuing on with the mini-series on tables, today we’re going to add a foreign key constraint to a table. Since we only have one table in our database so far, we’ll create a new table. The foreign key constraint will be created on the unique key in the Common.TestTable – the RowGuid column.

[codesyntax lang=”powershell” strict=”yes”]

[/codesyntax]

Most of this code was creating the second table where the foreign key constraint will be at. Actually building the foreign key is just the last few lines of code – creating a ForeignKey object, creating a ForeignKeyColumn object for each column and assigning it to the ForeignKey.Columns property, setting the ReferencedTable and its Schema, and finally creating the foreign key.