Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Foreign Key relationship between two Databases

I have two tables in two different databases. In table1 (in database1) there is a column called column1 and it is a primary key. Now in table2 (in database2) there is a column called column2 and I want to add it as a foreign key.

I tried to add it and it gave me the following error:

Msg 1763, Level 16, State 0, Line 1
Cross-database foreign key references are not supported. Foreign key Database2.table2.

Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.

How do I do that since the tables are in different databases.

like image 710
Sam Avatar asked Dec 15 '10 16:12

Sam


People also ask

Can you have a foreign key to a different database?

Since you want to keep all the business rules in the database your first thought is to use a Foreign Key constraint between the two databases, but when you try to create a foreign key between the two tables on the different databases you quickly learn that it is not possible.

What is foreign key relationship in database?

A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table. The table with the foreign key is called the child table, and the table with the primary key is called the referenced or parent table.

How do you set a foreign key in a one-to-one relationship?

Primary Key as Foreign Key One way to implement a one-to-one relationship in a database is to use the same primary key in both tables. Rows with the same value in the primary key are related. In this example, France is a country with the id 1 and its capital city is in the table capital under id 1.


1 Answers

You would need to manage the referential constraint across databases using a Trigger.


Basically you create an insert, update trigger to verify the existence of the Key in the Primary key table. If the key does not exist then revert the insert or update and then handle the exception.

Example:

Create Trigger dbo.MyTableTrigger ON dbo.MyTable, After Insert, Update As Begin     If NOT Exists(select PK from OtherDB.dbo.TableName where PK in (Select FK from inserted) BEGIN       -- Handle the Referential Error Here    END  END 

Edited: Just to clarify. This is not the best approach with enforcing referential integrity. Ideally you would want both tables in the same db but if that is not possible. Then the above is a potential work around for you.

like image 54
John Hartsock Avatar answered Oct 15 '22 13:10

John Hartsock