Quantcast
Channel: Solved » sql-server
Viewing all articles
Browse latest Browse all 48

Update Table With Join in Sql Server 2005

$
0
0

I need to update this table in SQL Server 2005 with data from its ‘parent’ table, see below:

sale

id (int)
udid (int)
assid (int)

ud

id  (int)
assid  (int)

sale.assid contains the correct value to update ud.assid. What query will do this? I’m thinking a join but I’m not sure if it’s possible.

Solution

It very much depends on which database you’re using. Here are the ways to do it in ANSI (aka should work on any database), MySQL, SQL Server, and Oracle. Be advised that the ANSI method will be much slower than the other two methods, but if you’re not using MySQL, SQL Server, or Oracle, it’s the only way to go.

ANSI:

update ud 
  set assid = (
               select sale.assid 
                 from sale 
                where sale.udid = ud.udid
              )
 where exists (
               select * 
                 from sale 
                where sale.udid = ud.udid
              );

MySQL:

update ud u
inner join sale s on
    u.id = s.udid
set u.assid = s.assid

SQL Server:

update u
set u.assid = s.assid
from ud u
    inner join sale s on
        u.id = s.udid

Oracle:

update
    (select
        u.assid as new_assid,
        s.assid as old_assid
    from ud u
        inner join sale s on
            u.id = s.udid) up
set up.new_assid = up.old_assid

The post Update Table With Join in Sql Server 2005 appeared first on Solved.


Viewing all articles
Browse latest Browse all 48

Trending Articles