SQL Server:不匹配时然后从表中插入

时间:2014-06-09 18:25:18

标签: sql sql-server-2008 merge

是否可以在插入时从合并的表中进行选择?如果是这样,我该怎么做呢。

这是我所拥有的,但它是在说

  

关键字' SELECT'

附近的语法不正确

代码:

MERGE INTO TblPrem As MERC 
Using PremSvcXRef As ICE ON MERC.Premise = ICE.OldLocationNum 
                         AND MERC.PremiseServiceSeqNum IS NULL 
                         AND ICE.PremiseServiceSeqNum = (SELECT Min(PremiseServiceSeqNum)
                                                         FROM PremServXRef
                                                         WHERE MERC.Premise = OldLocationNum) 
WHEN MATCHED THEN 
   UPDATE 
      SET MERC.IcePremise = ICE.PremiseId,
          MERC.MercPremise = ICE.OldLocationNum,
          MERC.PremiseServiceSeqNum  = ICE.PremiseServiceSeqNum,
          MERC.MercCustNu = ICE.OldCustNum,
          MERC.IceCustNu = ICE.CustId

WHEN NOT MATCHED THEN
   INSERT(Premise, Zone, Address, City, State, CustomerName, Status, 
          Notes, Exclude, LastUpdate, upsize_ts, FarmTap, MultiMeter, 
          Abandoned, CustID, PremiseServiceSeqNum, MercPremise, IcePremise, 
          MercCustNu, IceCustNu)
     SELECT TOP 1 
        *,
        ICE.PremiseServiceSeqNum,
        ICE.OldLocationNum,
        ICE.PremiseId,
        ICE.OldCustNum,
        ICE.CustId
     FROM 
        TblPremisesCopy A 
     WHERE 
        A.Premise = ICE.OldLocationNum;

进一步解释我试图做的事情:

有一个主要关键词' Premise'之前,它被改为关键词'前提'和' PremiseServiceSeqNum'我正在使用当前值更新它。匹配时,它会更新当前记录,当它不是我试图复制表格的行并用其他信息更新它时。

0 个答案:

没有答案