Foreign key problem with multiple db in one transaction

眉间皱痕 提交于 2020-01-17 06:03:18

问题


I have one db say DB1, on adding one column in one table (DB1.t1) on DB1, triggers and create replica of same row in table by same name (DB2.t1) in another DB2. Using the identity of inserted row I need to add some rows in another table (DB2.t2) in DB2.

Problem is, I need to insert in DB1.t1 and DB2.t2 in one transaction. When try to do that, DB1.t1 inserts fine, but since it is not committed, DB2.t1 does not contain the row, so DB2.t2 could not insert new rows (missing foreign key), still when data from application is sent properly.

One option is too commit DB1 transaction, and then do DB2 operation, but there are other functionality related. Please suggest best way to achieve it.


回答1:


Well, Id columns are not meaningful "keys", and they will trip you up all over the place. They are supposed to be meaningless, physical identifiers, and you have attached meaning to them. When you demand that the same Ids exist in another database.

Have you resolved the FK violation ? Most probably you have a totally different Id for the DB1 row, in DB2; and certainly different parent Ids.

You need to consistently not specify an Id value, and let the server fill it in, or always specify an Id value, in both databases.

The second problem is that you are not thniking transactionally. Multi-db transactions are no problem at all. So forget the Id column, what it contains, and use the real keys for the table, in both Dbs. The ids will be different, but who cares (that means release the need to attach meaning to the meaningless identifier).




回答2:


Do it all in one transaction in a stored proc. Look up how to to do transactions in Books online. Make sure to put in the rollback if it errors (Use try catch blocks). ALso get the identity from table1 using the OUTPUT clause or Scope_identity().



来源:https://stackoverflow.com/questions/4849788/foreign-key-problem-with-multiple-db-in-one-transaction

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!