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

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'附近的语法错误。

这里出了什么问题?


当前回答

我发现将UPDATE转换为SELECT很有用,可以在更新之前获得我想要更新的作为测试的行。如果我能准确地选择我想要的行,我就可以更新我想要更新的行。

DECLARE @expense_report_id AS INT
SET @expense_report_id = 1027

--UPDATE expense_report_detail_distribution
--SET service_bill_id = 9

SELECT *
FROM expense_report_detail_distribution erdd
INNER JOIN expense_report_detail erd
INNER JOIN expense_report er 
    ON er.expense_report_id = erd.expense_report_id 
    ON erdd.expense_report_detail_id = erd.expense_report_detail_id
WHERE er.expense_report_id = @expense_report_id

其他回答

你还没有完全掌握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是可以在运行时计算的东西,这样就不必担心结果是陈旧的。

使用MYSQL的用户

UPDATE table1 INNER JOIN table2 ON table2.id = table1.id SET table1.status = 0 WHERE table1.column = 20

似乎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给出了错误。

试着这样做:

    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

  ;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