代码之家  ›  专栏  ›  技术社区  ›  Santiago Palladino

使用绑定的多部分标识符更新SQL中的多个列

  •  3
  • Santiago Palladino  · 技术社区  · 15 年前

    我正在尝试使用子查询更新MS SQL语句中的多个列。一次搜索让我想到了:

    UPDATE table1
    SET col1 = a.col1, col2 = a.col2, col3 = a.col3 FROM
    (SELECT col1, col2, col3 from table2 where <expression>) AS a
    WHERE table1.col1 <expression>
    

    http://geekswithblogs.net/phoenix/archive/2009/10/13/update-multiple-columns-on-sql-server.aspx

    我的问题是内在的 WHERE 表达式I需要引用表1中的特定字段:

    UPDATE table1
    SET col1 = a.col1, col2 = a.col2, col3 = a.col3 FROM
    (SELECT col1, col2, col3 from table2 where table1.col0 = table2.col0) AS a
    WHERE table1.col1 <expression>
    

    运行该查询时,无法绑定“多部分标识符”table1.col0。 “。显然,当使用该语法时,SQL无法绑定子查询中的当前Table1记录。现在,我为每个字段重复子查询,并使用以下语法:

    UPDATE table1
    SET col1 = (subquery), col2 = (subquery)...
    

    但这会对每列执行一次子查询(非常昂贵),我希望避免这种情况。

    有什么想法吗?

    3 回复  |  直到 13 年前
        1
  •  9
  •   Ray    15 年前

    在SQL Server中,可以使用 from 更新查询中的子句。像在select中那样联接表。要更新的表必须包含在联接中。

    update table_1
      set field_1 = table_2.value_1
      from table_1
        inner join table_2
          on (table_1.id = table_2.id)
    
        2
  •  2
  •   Sadurskyy Serhiy    14 年前

    您的汽车使用交叉应用命令从子选择更新多个列

    UPDATE t1
    SET t1.col1 = a.col1, t1.col2 = a.col2, t1.col3 = a.col3 
    FROM table1 t1
    CROSS APPLY
    (SELECT col1, col2, col3 from table2 where table1.col0 = table2.col0) a(col1,col2,col3)
    
        3
  •  1
  •   edosoft    15 年前

    或者,如果不喜欢join语法,也可以使用它:

    UPDATE table1
    SET col1 = a.col1, col2 = a.col2, col3 = a.col3 
    FROM table1, table2 as a
    WHERE table1.col0 = a.col0
    AND table1.col1 <expression>