Tuesday, July 8, 2008

Update a table with data from a view

Well this was my first (that I can remember) update query using data from an outside source - in this case, a view. It was actually documented quite clearly in Books Online. Nevertheless, code example, in case it is of use:


UPDATE table SET table.apple = v.apple
FROM table as t
INNER JOIN view as v
ON t.id = v.id


Why I had to use aliases for this to work is more than I understand. Explanations? Comments?

3 comments:

Tiger said...

Did you mean the following wouldn't work?

UPDATE table SET table.apple = view.apple
FROM table
INNER JOIN view
ON table.id = view.id

Then I don't know why.

TB said...

I think they make you use the aliases because a view can have the same name as a table. Also, one of the tables in the view could potentially be the table you are updating. Therefore a different name would be in order. Same goes for the column aliases.

I'm not exactly sure that is right, but I seem to recall reading something about that once.

glayla said...

tiger - yes, that's what I mean; try it out.

TB - that would make sense except you have to do the same thing even if it is table to table.