0

我已经研究了几个小时的动态连接,并且在解决这个问题时遇到了问题。我将 XML 提要数据批量加载到临时 SQL 表中,然后从临时表中添加/更新生产表。但是,我也尝试使用条件逻辑在必要时保留数据。下面的代码基本上是对 Merge() 方法的复制,仅在 SQL Server 2008 及更高版本中可用(生产服务器为 2005)。具体来说,我需要在此查询中实现的条件逻辑是,如果临时表的 [eMail] 字段不为空,则更新生产表中的该字段。否则,不要更新生产服务器中的 [eMail] 字段(为了保存数据)。这是我尝试过的,由于语法不正确而无法工作:

UPDATE rt
SET rt.[AccountID] = tmp.[AccountID],
  rt.[CustNbr] = tmp.[CustNbr],
  rt.[ClientID] = tmp.[ClientID],
  rt.[ClientX] = tmp.[ClientX],
  rt.[CorpID] = tmp.[CorpID],
  rt.[fName] = tmp.[fName],
  rt.[lName] = tmp.[lName],
  rt.[Position] = tmp.[Position],
  rt.[eMail] = tmp.[eMail],
  rt.[ClientNotes] = tmp.[ClientNotes],
  rt.[DeptID] = tmp.[DeptID]
 FROM AccountClient rt
 IF(SELECT eMail FROM AccountClientTemp) <> ''
     INNER JOIN AccountClientTemp tmp
        ON  tmp.[fName] = rt.[fName]
        and tmp.[lName] = rt.[lName]
        --and tmp.[eMail] = rt.[eMail]
        and tmp.[Position] = rt.[Position]
        and tmp.[DeptID] = rt.[DeptID]
ELSE
    INNER JOIN AccountClientTemp tmp
        ON  tmp.[fName] = rt.[fName]
        and tmp.[lName] = rt.[lName]
        and tmp.[eMail] = rt.[eMail]
        and tmp.[Position] = rt.[Position]
        and tmp.[DeptID] = rt.[DeptID]
INSERT INTO AccountClient
        ([AccountID], [CustNbr], [ClientID], [CorpID], [fName], [lName], [Position],
         [eMail], [ClientNotes], [DeptID])
        SELECT  tmp.[AccountID], tmp.[CustNbr], tmp.[ClientID], tmp.[CorpID], tmp.[fName], tmp.[lName],
        tmp.[Position], tmp.[eMail], tmp.[ClientNotes], tmp.[DeptID]
        FROM AccountClientTemp tmp
        LEFT JOIN AccountClient rt
            ON tmp.[fName] = rt.[fName]
            and tmp.[lName] = rt.[lName]
            and tmp.[eMail] = rt.[eMail]
            and tmp.[Position] = rt.[Position]
        WHERE rt.[fName] IS NULL
         and rt.[lName] IS NULL
         and rt.[eMail] IS NULL
         and rt.[Position] IS NULL
4

1 回答 1

0

您不能在查询中间放置“if”语句。因此,您的更新应如下所示:

UPDATE rt
    SET rt.[AccountID] = tmp.[AccountID],
        rt.[CustNbr] = tmp.[CustNbr],
        rt.[ClientID] = tmp.[ClientID],
        rt.[ClientX] = tmp.[ClientX],
        rt.[CorpID] = tmp.[CorpID],
        rt.[fName] = tmp.[fName],
        rt.[lName] = tmp.[lName],
        rt.[Position] = tmp.[Position],
        rt.[eMail] = (case when tmp.[eMail] = '' then rt.eMail else tmp.eMail end),
        rt.[ClientNotes] = tmp.[ClientNotes],
        rt.[DeptID] = tmp.[DeptID]
    FROM AccountClient rt
         INNER JOIN AccountClientTemp tmp
         ON  tmp.[fName] = rt.[fName] and
             tmp.[lName] = rt.[lName] and
             (tmp.[eMail] = rt.[eMail] or tmp.eMail = '') and
             tmp.[Position] = rt.[Position] and
             tmp.[DeptID] = rt.[DeptID];

乍一看,INSERT 看起来不错。

于 2012-08-16T18:56:44.080 回答