update record from another record in same table

  • Hi, I'm looking for the best way to update pkid 1 = pkid 2

    update testTable

    set

    a.fname = b.fname

    from

    (select * from testTable where pkid = 1) as a

    join

    (select * from testTable where pkid = 2) as b

  • Marcus Farrugia (5/1/2013)


    Hi, I'm looking for the best way to update pkid 1 = pkid 2

    update testTable

    set

    a.fname = b.fname

    from

    (select * from testTable where pkid = 1) as a

    join

    (select * from testTable where pkid = 2) as b

    This:

    update dbo.testTable set

    fname = (select fname from dbo.testTable where pkid = 2)

    where

    pkid = 1;

  • update dbo.testTable set

    fname = (select fname from dbo.testTable where pkid = 2)

    where

    pkid = 1;

    Thanks Lynne!

    if there were multiple columns would I just do the same for each column, ie:

    update dbo.testTable set

    fname = (select fname from dbo.testTable where pkid = 2),

    lname = (select fname from dbo.testTable where pkid = 2),

    address = (select address from dbo.testTable where pkid = 2

    where

    pkid = 1;

  • Marcus Farrugia (5/1/2013)


    update dbo.testTable set

    fname = (select fname from dbo.testTable where pkid = 2)

    where

    pkid = 1;

    Thanks Lynne!

    if there were multiple columns would I just do the same for each column, ie:

    update dbo.testTable set

    fname = (select fname from dbo.testTable where pkid = 2),

    lname = (select fname from dbo.testTable where pkid = 2),

    address = (select address from dbo.testTable where pkid = 2

    where

    pkid = 1;

    Maybe you could try something along these lines if you have multiple columns:

    UPDATE tt1

    SET FName = tt2.FName,

    LName = tt2.LName,

    [Address] = tt2.[Address]

    FROM dbo.TestTable tt1 JOIN

    (SELECT 1 as pkid, FName, LName, [Address] FROM dbo.TestTable WHERE pkid=2) tt2

    ON tt1.pkid = tt2.pkid

    WHERE tt1.pkid=1

    Please note it is untested as you have supplied no test data or ddl.

Viewing 4 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply