简体   繁体   中英

Set column values in TableA to corresponding values from TableB if some value exist in TableC

I have a TableA that I just added two columns to, StartDate and StopDate. It also contain the column UserName.

I want to fill it with values from TableB that also has StartDate and StopDate. TableB has another column called UserId.

TableC has two columns, Id and Name.

This is what I want to do, explained with some kind of pseudocode:

for each row in TableB, where TableB.UserId exists in TableC.Id, take the corresponding row in TableA where TableA.UserName = TableC.Name and set the TableA.StartDate = TableB.StartDate & TableA.StopDate = TableB.StopDate.

I tried to create a join statement that would do it but the result was kind of embarrassing. Help would be much appreciated.

Edit: What I have tried:

UPDATE TableA 
SET STARTDATE = (
   SELECT TableB.StartDate
   FROM TableB
   WHERE TableB.UserId = (??? what should I write here)?

And then same for StopDate

You can achieve this using the "update-from" syntax. *I see you've already solved your question, but I'll post this as a possible alternative.

declare @TableA table (id int identity(1, 1), startDate datetime, stopDate datetime, userName varchar(20))
declare @TableB table (id int identity(1, 1), startDate datetime, stopDate datetime, userId int)
declare @TableC table (userId int, userName varchar(20))

insert into @TableA (userName)
select 'A' union all select 'B'

insert into @TableB (userId, startDate, stopDate)
select 1, '2015-01-01', '2015-01-31' union all select 2, '2015-12-01', '2015-12-31'

insert into @TableC
select 1, 'A' union all select 2, 'B'

update
    A
set
    A.startDate = B.startDate,
    A.stopDate = B.stopDate
from
    @TableA A
    inner join @TableC C on C.userName = A.userName
    inner join @TableB B on B.userId = C.userId

select
    *
from
    @TableA

I solved it, here is my solution

UPDATE TableA
SET StartDate = up.StartDate, EndDate = up.EndDate
FROM TableB up WHERE up.UserID = (SELECT Id from TableC u where u.Name = TableA.UserName)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM