我有两张不直接相关的表,比如......
表1
VoucherId | VoucherDate
-----------+-------------
V001 | 2014-12-09
V002 | 2016-01-10
表2
FinYearRef | FromDate | ToDate
-----------+------------+-----------
Y01 | 2014-07-01 | 2015-06-30
Y02 | 2015-07-01 | 2016-06-30
现在我向表1
添加了一列FRef
我希望从表2中FRef
更新FinYearRef
列,其中Table1.VoucherDate
介于Table2.FromDate
和Table2.ToDate
之间
答案 0 :(得分:0)
使用加入更新:
UPDATE T1
SET T1.FRef = T2.FinYearRef
FROM TABLE1 T1
JOIN TABLE2 T2
ON T1.VoucherDate BETWEEN T2.FromDate AND T2.ToDate
请注意,这将使用T2的最后一个匹配更新FRef。如果你想要第一个值,那么:
UPDATE TABLE1
SET T1.FRef =
(SELECT TOP 1 FinYearRef FROM TABLE2
WHERE TABLE1.VoucherDate BETWEEN T2.FromDate AND T2.ToDate)