我有2个数据库
Test1
Test2
我在每个数据库中都有Author
表,我想将AuthorId
从Test1
同步到Test2
。
在Test2
中还有另一个表格ProductAuthor
,其中包含f oreign Key constraint on AuthorID in Author table
。
我现在正在做的是
删除外键约束
更新两个表:作者和ProductAuthor
添加外键约束
--remove the foreign key constraint
ALTER TABLE [dbo].[ProductAuthor] DROP CONSTRAINT [FK_ProductAuthor_Author]
Update Test2.dbo.ProductAuthor set AuthorId = (
select distinct T1A.AuthorId from Test1.dbo.Author T1A
INNER JOIN Test2.dbo.Author T2A ON T1A.FirstName = T2A.firstname COLLATE Latin1_General_CI_AS and T1A.LastName = T2A.surname COLLATE Latin1_General_CI_AS
where T2A.AuthorId = ProductAuthor.AuthorId
) where ProductAuthor.AuthorId = 6793
Update Test2.dbo.Author set AuthorId = (
select Distinct T1A.AuthorId from Test1.dbo.Author T1A
INNER JOIN Test2.dbo.Author T2A ON T1A.FirstName = T2A.firstname COLLATE Latin1_General_CI_AS and T1A.LastName = T2A.surname COLLATE Latin1_General_CI_AS
where T1A.AuthorId = 106793) where Test2.dbo.AuthorId = 6793
--add the foreign key constraint
ALTER TABLE [dbo].[ProductAuthor] WITH NOCHECK ADD CONSTRAINT [FK_ProductAuthor_Author] FOREIGN KEY([AuthorId])
REFERENCES [dbo].[Author] ([AuthorId])
以上脚本更新了specific AuthorId from Test1.Author to Test2.Author and Test2.ProductAuthor
ASK:
我如何更改脚本以便它根据Test1.Author中的名字和姓氏更新Test2.Author和Test2.ProductAuthor中的所有行?
答案 0 :(得分:0)
我认为您要做的是更新并选择此处:
How to do 3 table JOIN in UPDATE query?
你可能只需要做一个基本的连接 - 即
JOIN (SELECT * FROM db1.author WHERE ....) as db1
SET db2.author = db1.ID
试一试,看看它是否有效。