SQL Server:根据同一个表中的其他行更新行

时间:2015-07-14 13:46:46

标签: sql sql-server

我在项目中使用SQL Server,我必须根据同一个表中的其他行更新某些行的列值。这是我的表:

| Name | Code | Locale
--------------------
| A    | ab   | en
| A    | cd   | ar
| A    | ef   | ru
| B    | gh   | ar

我需要根据Locale为“en”且在Name中具有相同值的行的Code值更新Locale不是“en”的行的Code值。保证Locale中“en”的每一行在Name中都有唯一的值。所以这就是我希望实现的目标

| Name | Code | Locale
--------------------
| A    | ab   | en
| A    | ab   | ar
| A    | ab   | ru
| B    | gh   | ar

我在SO Update row with data from another row in the same table找到了这个帖子,并尝试了以下方法但没有一个工作。

UPDATE mytable dt1, mytable dt2 
SET dt1.code = dt2.code 
WHERE dt1.NAME = dt2.NAME 
  AND dt1.code <> 'en' 
  AND dt2.code = 'en'

UPDATE mytable t1 
INNER JOIN mytable t2 ON t1.NAME = t2.NAME and t2.code = 'en' 
SET t1.code = t2.code;
WHERE t1.code <> 'en'

2 个答案:

答案 0 :(得分:3)

在SQL Server中,您可以使用join中的update执行此操作。正确的语法是:

update t
   set code = teng.code
   from mytable t join
        (select t2.*
         from mytable t2
         where t2.locale = 'en'
        ) teng
        on teng.name = t.name;

实际上,子查询并不是必需的:

update t
   set code = teng.code
   from mytable t join
        mytable teng
        on teng.name = t.name and teng.locale = 'en'

答案 1 :(得分:1)

使用子查询的另一种方式

UPDATE LocaleTable
   SET Code = ISNULL((SELECT TOP 1 Code FROM LocaleTable t WHERE t.Name = LocaleTable.Name and t.Locale = 'en' ORDER BY Code),Code)
WHERE Locale <> 'en'
相关问题