簡體   English   中英

如果TableC中存在某些值,則將TableA中的列值設置為TableB中的相應值

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

我有一個TableA,我剛剛將兩列添加到StartDate和StopDate。 它還包含UserName列。

我想用同樣具有StartDate和StopDate的TableB中的值填充它。 TableB的另一列稱為UserId。

TableC有兩列,Id和Name。

這是我想做的,用某種偽代碼解釋:

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.

我試圖創建一個可以執行此操作的join語句,但是結果有點尷尬。 幫助將不勝感激。

編輯:我曾嘗試:

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

然后對於StopDate同樣

您可以使用“ update-from”語法來實現。 *我看到您已經解決了您的問題,但我將其發布為可能的選擇。

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

我解決了,這是我的解決方案

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