我有2张桌子
Customer
(CustomerID int,Name varchar(20),OrderHistory xml)Order
(OrderID int,CustomerID int,OrderDate date)我想在OrderHistory
列的每一行中插入基于OrderDate
Customer
CustomerID
的{{1}}。
这是我的问题:
UPDATE Customer
SET OrderHistory = (SELECT OrderDate
FROM Order
WHERE CustomerID = 1
FOR XML AUTO)
WHERE CustomerID = 1
但是,我必须为每位新客户更改CustomerID
。有没有办法立即插入每个客户?
答案 0 :(得分:2)
将UPDATE ... FROM ...
构造应用于初始SQL以使其一次更新所有客户数据应该很简单:
UPDATE Customer
SET OrderHistory =
(SELECT OrderDate
FROM Order o
WHERE o.CustomerID = c.CustomerID
FOR XML AUTO)
FROM Customer c
答案 1 :(得分:0)
对于使用Join另一个表更新表,请使用下一个方法:
UPDATE A
SET foo = B.bar
FROM TableA A
JOIN TableB B
ON A.col1 = B.colx
WHERE ...
因此更新查询将如下:
UPDATE A
SET OrderHistory = B.OrderDate
FROM Customer A
JOIN Order B
ON A.CustomerID = B.CustomerID
答案 2 :(得分:-1)
我刚想通了:
DECLARE
@count int
SET
@count = 0
UPDATE Customer
WHILE @count < (SELECT COUNT (*) FROM Customer)
BEGIN
SET OrderHistory = (SELECT
OrderDate
FROM
Order
WHERE CustomerID = @count
FOR XML AUTO)
WHERE CustomerID = @count
SET @count = @count + 1
END