2015-09-28 33 views
0

我有一個TableA,我剛添加了兩列StartDate和StopDate。它還包含用戶名列。如果TableC中存在一些值,請將TableA中的列值設置爲TableB中的相應值

我想用TableB中的值來填充它,它也有StartDate和StopDate。 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.

我試圖創建一個連接語句,會做,但結果卻是一種尷尬。 幫助將不勝感激。

編輯:我曾嘗試:

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

然後同爲StopDate

+0

編輯您的問題,並提供樣品數據和預期結果。這真的會幫助其他人理解解釋。 –

+0

添加到@GordonLinoff說的,告訴我們你已經嘗試過了。 –

+0

請標記dbms產品,因爲答案可能取決於它。 – jarlh

回答

0

我解決了這個問題,這裏是我的解決方案

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) 
1

爲此,可以使用「更新實現來自「語法。 *我看到你已經解決了你的問題,但我會把它作爲一個可能的選擇。

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