Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
mavericky
Posting Yak Master
117 Posts |
Posted - 2011-05-19 : 16:40:55
|
| Hi All,is there a way I can add a foreign key between tables present in 2 different databases.suppose d1 and d2 are the databases.table t1 is present in d1.table t2 is present in d2.is it possible to have a foreign key between t1 and t2?Thanks in anticipation,Mavericky |
|
|
robvolk
Most Valuable Yak
15732 Posts |
Posted - 2011-05-19 : 16:48:41
|
| No, you'll have to create a trigger to manage that, or move a table to the other database. |
 |
|
|
mavericky
Posting Yak Master
117 Posts |
Posted - 2011-05-19 : 16:56:13
|
| Thanks robvolk. Can you tell me how to create such a trigger or some example i can refer to? |
 |
|
|
robvolk
Most Valuable Yak
15732 Posts |
Posted - 2011-05-19 : 17:11:27
|
| [code]USE D2GOCREATE TRIGGER T2_Insert_Update_FK ON T2 FOR INSERT, UPDATE ASSET NOCOUNT ONIF EXISTS(SELECT * FROM inserted iWHERE NOT EXISTS(SELECT * FROM D1..T1 WHERE IDCOL=i.IDCOL)) BEGIN RAISERROR('Violation of pseudo-foreign key.', 16, 1) ROLLBACK TRANENDGOUSE D1GOCREATE TRIGGER T1_Delete_FK ON T1 FOR DELETE ASSET NOCOUNT ONIF EXISTS(SELECT * FROM deleted dWHERE EXISTS(SELECT * FROM D2..T2 WHERE IDCOL=d.IDCOL)) BEGIN RAISERROR('Violation of pseudo-foreign key.', 16, 1) ROLLBACK TRANENDGO[/code]The second trigger protects against deleting rows from T1 that exist in T2, and is optional.Another option you might consider is moving T2 to D1 and creating a synonym in D2 for it:[code]USE D2GOCREATE SYNONYM T2 FOR D1..T2[/code]You can insert into the synonym and it will go into the correct table in D1. This requires SQL Server 2005 or higher. The advantage is you can create a proper foreign key. The downside is if you had related tables in D2 you can't create foreign keys to the synonym. |
 |
|
|
X002548
Not Just a Number
15586 Posts |
|
|
robvolk
Most Valuable Yak
15732 Posts |
Posted - 2011-05-19 : 17:23:48
|
Sure, I'd love to mow a lawn under 1/2 acre in size.BTW, I have 12-18 months of NO POSTS AT ALL to make up for. You had all of 2006-2007 to yourself. |
 |
|
|
|
|
|
|
|