我的问题是:我有2个SQL服务器,我使用链接服务器从server1更新server2上的表。 我正在使用此查询:
insert into [server2].[db2].[dbo].[pcodes] (parcode,pname,unit,typ) select parcode,pname,unit,typ from [server1].[db1].[dbo].[pcodes] where not exists (select parcode,pname,unit,typ from [server2].[db2].[dbo].[pcodes])
代码仅在server2上的表为空时才有效,所以当我第一次执行查询时它会工作,但之后我在server1上添加新记录并执行查询时,我得到了(0行受影响)。任何建议PLZ? 我想让你知道,如果server1中的新记录或编辑记录在server2中不存在,我想更新server2表。 无论如何,谢谢你们。 UODATE:
检查上面的图像,当记录是server1中的9条记录而server2中的表为空时,查询工作,所有9条记录都已插入server2,之后,我在server1中添加了一条新记录,这是第10条记录,我执行了上述查询,得到了(0行影响)。为什么没有插入新记录?
在not exists语句中你需要有where条件,你的查询缺少,
INSERT INTO [server2].[db2].[dbo].[pcodes] (parcode,pname,unit,typ)
SELECT parcode,pname,unit,typ
FROM [server1].[db1].[dbo].[pcodes] a
WHERE NOT EXISTS
(SELECT parcode,pname,unit,typ from [server2].[db2].[dbo].[pcodes] b
WHERE a.parcode=b.parcode and a.pname=b.pname and a.unit=b.unit and a.typ=b.typ )