Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Foreign Keys across database boundaries - techniques for enforcement

I have two separate SQL Server 2005 databases (on the same server)

  • security database
  • main application database

  • The security database has a user table with everything needed to authenticate. -

  • The application database has a person table with extended user details. There is a 1-1 mapping between the security database user table and the application database person table.

I want to enforce a mapping between the user and the person table. I'm assuming that foreign keys can't be mapped across databases thus I am wondering what to do to enforce the integrity of the relationship.

like image 293
AJM Avatar asked Mar 02 '11 11:03

AJM


1 Answers

Cross database foreign keys are indeed not supported

    Msg 1763, Level 16, State 0, Line 2
    Cross-database foreign key references are not supported.

If you really want to enforce the referential integrity on the database side you will have to rely on triggers. (which I don't recommend)

to make your code more maintainable you could create synonyms for the tables you want to check referential integrity on.

      CREATE SYNONYM myTable FOR otherdatabase.dbo.myTable;

This would be to make the "manual" checks easier, as you can not create foreign keys on a synonym.

like image 74
Filip De Vos Avatar answered Oct 12 '22 17:10

Filip De Vos