1

I have 2 tables

  • Customer (CustomerID int, Name varchar(20), OrderHistory xml)
  • Order (OrderID int, CustomerID int, OrderDate date)

And I would like to insert into every row in OrderHistory column, an OrderDate of that Customer based on CustomerID.

Here is my query:

UPDATE Customer
SET OrderHistory = (SELECT OrderDate
                    FROM Order
                    WHERE CustomerID = 1
                    FOR XML AUTO)
WHERE CustomerID = 1

However, I have to change CustomerID for every new customer. Is there any way to insert into every customer at once ?

0

3 Answers 3

2

Applying UPDATE ... FROM ... construct to your initial SQL to make it update all customer data at once should be straightforward :

UPDATE Customer
SET OrderHistory = 
    (SELECT OrderDate
    FROM Order o
    WHERE o.CustomerID = c.CustomerID
    FOR XML AUTO)
FROM Customer c
Sign up to request clarification or add additional context in comments.

Comments

0

For Updating table via using Join another table use the next Approach:

UPDATE A
SET foo = B.bar
FROM TableA A
JOIN TableB B
ON A.col1 = B.colx
WHERE ...

So the update query will be as next:

UPDATE A
SET OrderHistory = B.OrderDate
FROM Customer A
JOIN Order B
ON A.CustomerID = B.CustomerID 

Comments

-1

I just figured out:

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

1 Comment

Slow because you're running a select count in a loop, assumes that customer number has no gaps, and lastly unnecessarily uses a loop. There are many more far superior suggestions here - it would be a good idea to learn from them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.