Adding Foreign Keys after a table is created in SQL Server
Well, you knew exactly what you needed when you created a table. Only now when you created a child table, the child table does not update with the information from your main table. Or worse you deleted something from your primary table and it still lives in the child table. You need a foreign key, my friend. This is how you define one after you’ve created your table.
1 2 3 4 5 |
<span style="color: #0000ff;">ALTER TABLE</span> My_Child_Table <span style="color: #0000ff;">ADD CONSTRAINT</span> FK_User_ID <span style="color: #0000ff;">FOREIGN KEY</span> ( User_ID_In_Child_Table ) <span style="color: #0000ff;">REFERENCES</span> My_Primary_Table ( User_ID_In_Primary_Table ) <span style="color: #0000ff;">ON DELETE CASCADE ON UPDATE CASCADE</span> |
The last two lines are important. In this example, if the user id in the primary table is modified or deleted, the change will cascade to the child table. This ensures … Continue reading Adding Foreign Keys after a table is created in SQL Server