您可以采取两步走的方法。不是最有效的,但对您来说可能已经足够了。将第二次更新中的值更改为与您想要的周末天数相对应:
update Table2
set Estimated_Delivery_Date =
dateadd(
day,
(select "No:of Days" from Table1 t1 where t1.Location = Table2.Location),
Ready_To_Ship_Date
);
update Table2
set Estimated_Delivery_Date =
dateadd(
day,
case
when datepart(weekday, Estimated_Delivery_Date) = 7 then 2
when datepart(weekday, Estimated_Delivery_Date) = 1 then 1
else 0 /* redundant with the where */
end,
Estimated_Delivery_Date
)
where datepart(weekday, Estimated_Delivery_Date) in (1, 7);
这并不是说不能一步完成;它只是变得更难阅读:
update Table2
set Estimated_Delivery_Date =
dateadd(
day,
coalesce((select "No:of Days" from Table1 t1 where t1.Location = Table2.Location), 0)
+ case
datepart(weekday, dateadd(
day,
(select "No:of Days" from Table1 t1 where t1.Location = Table2.Location),
Ready_To_Ship_Date
))
when 7 then 2
when 1 then 1
else 0
end,
Ready_To_Ship_Date
)
end
第二个查询还通过coalesce() 处理 Table1 中的失败查找。我不认为你会有这个问题。
还要注意,有些人会在更新中使用inner join 语法而不是重复子查询。虽然这是非标准的,但它有很多怪癖,这使它成为避免的一件好事。优化器可能仍然可以解决所有问题。
现在,如果您需要动态计算各个国家/地区的周末工作日,您需要在某处查找该数据。如果您没有找到通用解决方案,它也可能取决于您服务器的区域设置。
您可能更喜欢更健壮的东西,但一个简单的选择是假设您将列 WeekendDay1 和 WeekendDay2 添加到 Table1 使用美国日编号和匹配的服务器设置 @@datefirst。
update Table2
set Estimated_Delivery_Date =
dateadd(
day,
coalesce((select "No:of Days" from Table1 t1 where t1.Location = Table2.Location), 0)
+ case
datepart(weekday, dateadd(
day,
(select "No:of Days" from Table1 t1 where t1.Location = Table2.Location),
Ready_To_Ship_Date
))
when (select WeekendDay1 from Table1 t1 where t1.Location = Table2.Location)
then 2
when (select WeekendDay2 from Table1 t1 where t1.Location = Table2.Location)
then 1
else 0
end,
Ready_To_Ship_Date
)
end