我想在一个表中更新一个列,在其他表上进行连接,例如:

UPDATE table1 a 
INNER JOIN table2 b ON a.commonfield = b.[common field] 
SET a.CalculatedColumn= b.[Calculated Column]
WHERE 
    b.[common field]= a.commonfield
AND a.BatchNO = '110'

但它在抱怨:

警报170,15层,状态1,2号线 第2行:'a'附近的语法错误。

这里出了什么问题?


当前回答

Try:

UPDATE table1
SET CalculatedColumn = ( SELECT [Calculated Column] 
                         FROM table2 
                         WHERE table1.commonfield = [common field])
WHERE  BatchNO = '110'

其他回答

似乎SQL Server 2012也可以处理旧的Teradata更新语法:

UPDATE a
SET a.CalculatedColumn= b.[Calculated Column]
FROM table1 a, table2 b 
WHERE 
    b.[common field]= a.commonfield
AND a.BatchNO = '110'

如果我没记错,当我尝试类似的查询时,2008R2给出了错误。

你还没有完全掌握SQL Server专有的UPDATE FROM语法。也不知道为什么你需要在CommonField上加入,然后还对它进行过滤。试试这个:

UPDATE t1
  SET t1.CalculatedColumn = t2.[Calculated Column]
  FROM dbo.Table1 AS t1
  INNER JOIN dbo.Table2 AS t2
  ON t1.CommonField = t2.[Common Field]
  WHERE t1.BatchNo = '110';

如果你在做一些愚蠢的事情——比如不断地试图将一列的值设置为另一列的总和(这违反了避免存储冗余数据的原则),你可以使用CTE(公共表表达式)——请参阅这里和这里了解更多细节:

;WITH t2 AS
(
  SELECT [key], CalculatedColumn = SUM(some_column)
    FROM dbo.table2
    GROUP BY [key]
)
UPDATE t1
  SET t1.CalculatedColumn = t2.CalculatedColumn
  FROM dbo.table1 AS t1
  INNER JOIN t2
  ON t1.[key] = t2.[key];

之所以这么做很愚蠢,是因为每次table2中的任何一行发生变化时,都必须重新运行整个更新。SUM是可以在运行时计算的东西,这样就不必担心结果是陈旧的。

另一种方法是使用MERGE

  ;WITH cteTable1(CalculatedColumn, CommonField)
  AS
  (
    select CalculatedColumn, CommonField from Table1 Where BatchNo = '110'
  )
  MERGE cteTable1 AS target
    USING (select "Calculated Column", "Common Field" FROM dbo.Table2) AS source ("Calculated Column", "Common Field")
    ON (target.CommonField = source."Common Field")
    WHEN MATCHED THEN 
        UPDATE SET target.CalculatedColumn = source."Calculated Column";

-Merge是SQL标准的一部分

-我也很确定内部连接更新是不确定的。 类似的问题,答案是这样说的 http://ask.sqlservercentral.com/questions/19089/updating-two-tables-using-single-query.html

试着这样做:

    UPDATE a 
    SET a.CalculatedColumn= b.[Calculated Column]
    FROM table1 a INNER JOIN table2 b ON a.commonfield = b.[common field] 
    WHERE a.BatchNO = '110'
MERGE table1 T
   USING table2 S
      ON T.CommonField = S."Common Field"
         AND T.BatchNo = '110'
WHEN MATCHED THEN
   UPDATE
      SET CalculatedColumn = S."Calculated Column";