Reputation: 2129
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
Upvotes: 0
Views: 45
Reputation: 11
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
Upvotes: 1
Reputation: 2129
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)
Upvotes: 0