|
Home > Archive > Microsoft SQL Server forum > July 2005 > Update queries using more than one table
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
Update queries using more than one table
|
|
| Colin Spalding 2005-07-22, 7:23 am |
| In Access, if I want to update one table with information from another,
all I need to do is to create an Update query with the two tables, link
the primary keys and reference the source table(s)/column(s) with the
destination table(s)/column(s). How do I achieve the same thing in SQL?
Regards
Colin
*** Sent via Developersdex http://www.droptable.com ***
| |
| Simon Hayes 2005-07-22, 7:23 am |
| See Example C under UPDATE in Books Online, and also "Changing Data
Using the FROM Clause".
Simon
| |
| David Portas 2005-07-22, 7:23 am |
| Did you lookup the UPDATE statement in Books Online? It has several
examples:
http://msdn.microsoft.com/library/d..._ua-uz_82n9.asp
Do note the warning about the proprietary UPDATE FROM syntax:
"The results of an UPDATE statement are undefined if the statement
includes a FROM clause that is not specified in such a way that only
one value is available for each column occurrence that is updated (in
other words, if the UPDATE statement is not deterministic)."
That should be common sense but I've seen too many people get tripped
up by this issue. The problem is that this unpredictable behaviour is
silent. No error or warning is given so a serious bug could go
undetected. Check and test your code carefully. The alternative is to
use a correlated subquery:
UPDATE Table1
SET col1 =
(SELECT Table2.col1
FROM Table2
WHERE Table2.col2 = Table1.col2);
I prefer that syntax because it always seems clearer and more logical
to me, also it is standard SQL rather than a Microsoft invention and
finally it doesn't suffer from the bug-feature just described (an error
is reported if the subquery yields more than a single value per row).
Admittedly the proprietary UPDATE FROM version is more concise in some
cases and frequently the proprietary version has the advantage on
performance.
Hope this helps.
--
David Portas
SQL Server MVP
--
| |
| Colin Spalding 2005-07-22, 11:23 am |
| Thanks Simon it worked a treat.
Regards
Colin
*** Sent via Developersdex http://www.droptable.com ***
|
|
|
|
|