1

假设有两个表:Remote_tableMy_table

Remote_table有 6 列:

PROJECT   JOB_TYPE   MONTH  YEAR**       HOURS     IS_DELETED
134393     70         1       2013      30     0
134393     70         2       2013      50     0
134393     70         3       2013      80     0
134393     70         10      2012      10     0
134393     70         11      2012      0      0
134393     70         12      2012      15     0

My_tableremote_table.

我试图remote_table通过这个查询只复制新记录:

SELECT    *
FROM [remote_DB].[LudanProjectManager].[dbo].Remote_table            
EXCEPT           
SELECT    *
FROM My_table

remote_table它工作正常,但是当对小时列进行更改时,我得到一个重复的主键异常。

任何人都可以想出一种方法来仅复制新记录,remote_table并且如果对旧记录进行了更改,则可以识别它们并更新my_table相应的记录?

4

3 回答 3

2

由于您使用的是 SQL Server 2008,因此您可以使用MERGE

MERGE INTO My_table AS TGT
USING Remote_table AS SRC
  ON TGT.PROJECT = SRC.PROJECT, -- This is the matching condition. 
     TGT.YEAR    = SRC.YEAR,
   ---
WHEN NOT MATCHED THEN
  INSERT(PROJECT, JOB_TYPE, MONTH, YEAR, HOURS, IS_DELETED)
  VALUES(SRC.PROJECT, SRC.JOB_TYPE, SRC.MONTH, SRC.YEAR, SRC.HOURS,
         SRC.IS_DELETED);

注意:

  • 匹配和不匹配的行是根据ON子句中指定的代码来确定的,您可能需要使用额外的条件来限制匹配的行,, TGT.Year = SRC.TGT, ..或者PROJECT只使用ON TGT.PROJECT = SRC.PROJECT.
  • 您必须以MEREGE分号结束语句。这是强制性的。
  • INSERT语句中没有INTO TableName,因为目标表的名称已经在MERGE子句中定义。
于 2012-10-09T09:41:57.093 回答
1

尝试这个:

 MERGE INTO My_table T
USING 
    Remote_table R
    ON T.PROJECT    = R.PROJECT   
WHEN MATCHED THEN
    UPDATE SET
       T.JOB_TYPE=R.JOB_TYPE
       T.MONTH  =R.MONTH  
       T.YEAR =R.YEAR
       T.HOURS =R.HOURS
       T.IS_DELETED=R.IS_DELETED
WHEN NOT MATCHED THEN
    INSERT (T.PROJECT,T.JOB_TYPE,T.MONTH,T.YEAR,T.HOURS,T.IS_DELETED)
    VALUES (R.PROJECT,R.JOB_TYPE,R.MONTH,R.YEAR,R.HOURS,R.IS_DELETED);  
于 2012-10-09T09:47:54.057 回答
0

识别新:

SELECT * FROM [remote_DB].[LudanProjectManager].[dbo].Remote_table RT
WHERE NOT EXISTS
(
   SELECT 1 FROM My_table MT WHERE MT.PROJECT=RT.PROJECT
)

识别变化:

SELECT * FROM [remote_DB].[LudanProjectManager].[dbo].Remote_table RT
INNER JOIN My_table MT ON RT.PROJECT=MT.PROJECT
WHERE RT.JOB_TYPE   <> MT.OB_TYPE
OR    RT.MONTH      <> MT.MONTH  
OR    RT.YEAR       <> MT.YEAR
OR    RT.HOURS      <> MT.HOURS 
OR    RT.IS_DELETED <> MT.IS_DELETED 
于 2012-10-09T09:35:52.267 回答