用于更新错误输入值的SQL查询

时间:2017-10-26 14:12:34

标签: sql sql-server tsql sql-server-2012

我正在尝试使用城镇列更新邮政编码列,因为错误地输入了城镇列中的某些条目(用户输入的邮政编码而不是城镇名称),所以我写了一个查询来更新邮政编码列的邮政编码值进入城镇专栏:

UPDATE      dbo.ClientLocations
SET         Postcode = cl.Town
FROM        ClientLocations cl INNER JOIN Clients AS c 
            ON cl.ClientId = c.Id
WHERE   (cl.Town IS NOT NULL) AND 
        (cl.Town <> '') AND 
        (cl.Archived IS NULL OR cl.Archived = 0) AND 
        (cl.Postcode IS NULL) AND 
        (c.IsArchived IS NULL OR c.IsArchived = 0)  AND
        (cl.Town <> 'Norwich' AND  cl.Town <> 'Ireland') and 
        cl.ClientId not in (27858,45444)

1 个答案:

答案 0 :(得分:1)

我猜你发现代码不起作用,因为所有行都在更新。您需要在update

中使用表别名
UPDATE cl
    SET Postcode = cl.Town
    FROM ClientLocations cl INNER JOIN
         Clients AS c ON cl.ClientId = c.Id
    WHERE  (cl.Town IS NOT NULL) AND (cl.Town <> '') AND (cl.Archived IS NULL OR
           cl.Archived = 0) AND (cl.Postcode IS NULL) AND (c.IsArchived IS NULL OR
               c.IsArchived = 0)  AND  (cl.Town <> 'Norwich' AND  cl.Town <> 'Ireland') and cl.ClientId not in (27858, 45444);

您可能还有另一个问题,但您可能会update执行您想要的操作。