SQL UPDATE,其中两个字段位于同一行

时间:2018-09-24 16:34:54

标签: sql sql-server

我有3张桌子,Order, Customer, OrderCustomer

订单

order_number    customer_number
----------------------------------    
1               null
2               null

客户

customer_number    customer_code    
-----------------------------------
  33               z-99
  34               z-100

OrderCustomer

order_number customer_code
----------------------------
  1            z-99
  2            z-100

我确实尝试过:

UPDATE order
SET o.[customer_number] = c.[customer_number]
FROM order AS o
INNER JOIN orderCustomer AS oc ON o.[order_number] = oc.[order_number]
INNER JOIN customer AS c ON oc.[customer_code] = c.customer_code

但是运行上面的查询会引发错误:

  

无法绑定多部分标识符“ o.customer_number”。

如何使用order.customer_number的值更新customer.customer_number

2 个答案:

答案 0 :(得分:0)

update使用别名:

UPDATE o
    SET o.[customer_number] = c.[customer_number]
    FROM order o JOIN
         orderCustomer oc
         ON o.[order_number] = oc.[order_number] JOIN
         customer AS c
         ON oc.[customer_code] = c.customer_code;

SQL Server神奇地识别出ordero子句中的FROM的语法。别名替换后使用表名会使我感到困惑。

SQL Server认为您要更新的内容称为“订单”,而不是“ o”,因此SET中的引用会导致问题。

实际上,SQL Server仅允许您更新一个表,因此别名在set中是多余的:

UPDATE o
    SET [customer_number] = c.[customer_number]
    FROM order o JOIN
         orderCustomer oc
         ON o.[order_number] = oc.[order_number] JOIN
         customer AS c
         ON oc.[customer_code] = c.customer_code;

这也可以与UPDATE order一起使用,但是我强烈建议您在定义别名后再使用它。

答案 1 :(得分:0)

您需要更新别名而不是表。另外,不要在SET子句中包含别名。最后但并非最不重要的一点是,您必须将表顺序包装在方括号中。您确实应该避免使用保留字作为对象名称。

UPDATE o
SET [customer_number] = c.[customer_number]
FROM [order] AS o
INNER JOIN orderCustomer AS oc
    ON o.[order_number] = oc.[order_number]
INNER JOIN customer AS c
    ON oc.[customer_code] = c.customer_code