基于连接选择更新SQL记录

时间:2011-07-27 20:16:58

标签: sql-server

这看起来非常简单,我想我只想验证并确保我正确地做到这一点。

基本上我想对这些记录运行UPDATE:

SELECT     contact.company, contact.coaddress, contact.costate, contact.cocity, contact.cozip, contact.phonebusiness, dial.AgentID, dial.Attempts, dial.CRC
FROM         contact LEFT OUTER JOIN
                  dial ON contact.DialID = dial.DialID
WHERE     (dial.AgentID > '-1') AND (contact.cozip LIKE '600%' OR
                  contact.cozip LIKE '601%' OR
                  contact.cozip LIKE '606%' OR
                  contact.cozip LIKE '608%' OR
                  contact.cozip LIKE '605%' OR
                  contact.cozip LIKE '604%' OR
                  contact.cozip LIKE '613%' OR
                  contact.cozip LIKE '611%')

我在SELECT语句中找回了正确的结果。我现在需要更新这些记录:

UPDATE    dial
SET              ProjectID = '60'
FROM         dial INNER JOIN
                  contact ON dial.DialID = contact.DialID
WHERE     (dial.AgentID > '-1') AND (contact.cozip LIKE '600%' OR
                  contact.cozip LIKE '601%' OR
                  contact.cozip LIKE '606%' OR
                  contact.cozip LIKE '608%' OR
                  contact.cozip LIKE '605%' OR
                  contact.cozip LIKE '604%' OR
                  contact.cozip LIKE '613%' OR
                  contact.cozip LIKE '611%')

这看起来是否正确?有没有更有效的方法呢?

2 个答案:

答案 0 :(得分:4)

是的,这看起来是正确的。

有一些类似的技巧,我个人喜欢别名。别名d清楚地表明JOIN中正在更新哪个表。 LIKE中的[]表示范围或集合

UPDATE
    d
SET 
    ProjectID = '60'
FROM
    dial d
    INNER JOIN
    contact ON d.DialID = contact.DialID
WHERE
   (d.AgentID > -1) --edit, int. Not varchar
   AND 
   (contact.cozip LIKE '60[016854]%' OR contact.cozip LIKE '61[13]%')

AgentID也应该是数字-1吗?

答案 1 :(得分:1)

对于我来说,这似乎是基于JOIN删除或更新的正确语法。

请注意,您可以使用子查询和IN运算符,例如“UPDATE拨打SET ProjectID = '60'WELERE DialID in(SELECT DialID from dial ...)”。