Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreign keys on table from different database

I have two databases in SQL Server and i have a common table for both the databases an important big table which holds the foreign keys to other tables. The problem is the Table is in DatabaseA, and I need to refer foreign keys to this table from DatabaseB.

I know SQL doesn't support cross database referential integrity so what's the best way to achieve this? I am thinking of combining two databases and make into single database - it wouldn't matter aside from the increase in complexity.

Any suggestions?

like image 317
SweetGangster Avatar asked Sep 14 '09 23:09

SweetGangster


People also ask

Can we have foreign key from another database?

FOREIGN KEY constraints can reference another column in the same table, and is referred to as a self-reference. A FOREIGN KEY constraint specified at the column level can list only one reference column. This column must have the same data type as the column on which the constraint is defined.

Can a table have multiple foreign keys from same table?

A table can have multiple foreign keys based on the requirement.

Can two tables share a foreign key?

When you're using a foreign key to reference a column in another table, the datatypes of both tables have to be the same. For example, if the referencing column where you're declaring the foreign key uses the INT data type, then the referenced column must be INT as well.

Can a foreign key reference two tables SQL?

The FOREIGN KEY constraint is a key used to link two tables together. A FOREIGN KEY is a field (or collection of fields) in one table that refers to the PRIMARY KEY in another table.


1 Answers

I would avoid doing this if I could - can you just keep both tables in one datbase and use an FK?

Parent and Child Tables Are in Different Databases.

Although you cannot use a foreign key in this situation, there are workarounds – you can use either triggers or UDFs wrapped in check constraints. Either way, your data integrity is not completely watertight: if the database with your parent table crashes and you restore it from a backup, you may easily end up with orphans.

Parent-Child Relationship Is Enforced by Triggers.

There are quite a few situations when triggers do not fire, such as:

· A table is dropped.

· A table is truncated.

· Settings for nested and/or recursive triggers prevent a trigger from firing.

Also a trigger may be just incorrect. Either way, you may end up with orphans in your database.

like image 198
A-K Avatar answered Oct 13 '22 18:10

A-K