时间:2021-07-01 10:21:17 帮助过:6人阅读
根据一个表的中主键字段和数据字段从其它数据库中找到结构相同的同名表,并同步相同表的数据。 无 USE [CMS2]GODECLARE @sql NVARCHAR(MAX) SET @sql=N'MERGE [dbo].[RolePermission] targetUSING [CMS].[dbo].[RolePermission] sourceON target.['+STUFF((SE
根据一个表的中主键字段和数据字段从其它数据库中找到结构相同的同名表,并同步相同表的数据。 <无>USE [CMS2] GO DECLARE @sql NVARCHAR(MAX) SET @sql=N'MERGE [dbo].[RolePermission] target USING [CMS].[dbo].[RolePermission] source ON target.['+STUFF( (SELECT N'] AND target.[' + [COLUMN_NAME] + N']=source.[' + [COLUMN_NAME] FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE SUBSTRING([CONSTRAINT_NAME],1,2)='PK' AND [TABLE_NAME] = 'RolePermission' FOR XML PATH('')),1,14,N'')+'] WHEN MATCHED THEN UPDATE SET target.['+STUFF( (SELECT N'],target.[' + [COLUMN_NAME] + N']=source.[' + [COLUMN_NAME] FROM INFORMATION_SCHEMA.COLUMNS WHERE [TABLE_NAME] = 'RolePermission' FOR XML PATH('')),1,10,N'')+'] WHEN NOT MATCHED THEN INSERT VALUES(['+STUFF( (SELECT N'],[' + [COLUMN_NAME] FROM INFORMATION_SCHEMA.COLUMNS WHERE [TABLE_NAME] = 'RolePermission' FOR XML PATH('')),1,3,N'')+N']) WHEN NOT MATCHED BY SOURCE THEN DELETE;' EXEC sp_executesql @sql