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

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

这里出了什么问题?


当前回答

似乎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 mytable
         SET myfield = CASE other_field
             WHEN 1 THEN 'value'
             WHEN 2 THEN 'value'
             WHEN 3 THEN 'value'
         END
    From mytable
    Join otherTable on otherTable.id = mytable.id
    Where othertable.somecolumn = '1234'

这里有更多的选择。

另一种方法是使用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

使用MYSQL的用户

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

我想,这就是你要找的。

UPDATE
    Table1
SET
    Table1.columeName =T1.columeName * T2.columeName
FROM 
    Table1 T1
    INNER JOIN Table2 T2
        ON T1.columeName = T2.columeName;

我发现将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