Skip to content
Advertisement

T-SQL – Adding FK to table, make it do drop/null/efault automagically?

If I had two tables where I need to add a new foreign key to, say:

If there are records in the release_user table that do not have a matching ID in the user_table, the command will fail. I expect that.

However, is there a way to create the FK, and have it automatically delete (DELETE CASCADE) the records that would cause the FK to fail?

(Or, for example, if I used DELETE SET NULL, would null out the record’s field in the release_user table?)

Advertisement

Answer

You could delete them first?

DB_FIDDLE

Then, add your constraint.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement