我有一个复杂的select语句,例如:
SELECT *
FROM [Orders] a
INNER JOIN [Customers] b ON a.CustomerID = b.CustomerID
WHERE CustomerName LIKE '%Wilman%'
这给了我需要的行,然后我希望能够UPDATE
几乎这样的行:
UPDATE ([Orders] a
INNER JOIN [Customers] b ON a.CustomerID = b.CustomerID
WHERE CustomerName LIKE '%Wilman%')
SET ShipperID = 10
显然这不起作用,但我在Microsoft SQL Server中使用哪种逻辑?
答案 0 :(得分:2)
必须是:
UPDATE
Orders
SET
ShipperID = 10
FROM
[Orders] a INNER JOIN [Customers] b on a.CustomerID=b.CustomerID
WHERE
CustomerName LIKE '%Wilman%
答案 1 :(得分:1)
只要SELECT
语句返回唯一列名并满足可更新视图的条件,您就可以将其放入派生表或CTE中并更新它。
UPDATE (SELECT a.ShipperID
FROM [Orders] a
INNER JOIN [Customers] b
ON a.CustomerID = b.CustomerID
WHERE CustomerName LIKE '%Wilman%') AS T
SET ShipperID = 10
答案 2 :(得分:0)
您需要UPDATE/FROM
UPDATE o
SET ShipperID = 10
FROM Orders o
INNER JOIN Customers c ON c.CustomerID = o.CustomerID
WHERE c.CustomerName LIKE '%Wilman%'
答案 3 :(得分:0)
您可以使用common table expression。假设ShipperID
是Orders
的列,并假设CustomerName
是Customers
的列(顺便提一下,最好的做法是始终在JOIN
中为您的列添加前缀防止未来架构更改出现意外):
WITH OrdersToUpdate AS (
SELECT [Orders].*
FROM [Orders]
INNER JOIN [Customers] ON [Orders].CustomerID = [Customers].CustomerID
WHERE [Customers].CustomerName LIKE '%Wilman%'
)
UPDATE OrdersToUpdate SET ShipperID = 10;
此技术特别有用,因为它可以让您在不重写查询的情况下查看将更新(或删除,如果您使用DELETE
)。