简体   繁体   English

如果TableC中存在某些值,则将TableA中的列值设置为TableB中的相应值

[英]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. 我有一个TableA,我刚刚将两列添加到StartDate和StopDate。 It also contain the column UserName. 它还包含UserName列。

I want to fill it with values from TableB that also has StartDate and StopDate. 我想用同样具有StartDate和StopDate的TableB中的值填充它。 TableB has another column called UserId. TableB的另一列称为UserId。

TableC has two columns, Id and Name. TableC有两列,Id和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. 我试图创建一个可以执行此操作的join语句,但是结果有点尴尬。 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 然后对于StopDate同样

You can achieve this using the "update-from" syntax. 您可以使用“ update-from”语法来实现。 *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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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