当值丢失时更新数据库表
我有两个表:
Bill:
create table Bill(
BillDate datetime,
Amount decimal(10,2) ,
BillCurrency varchar(3) ,
ReportingCurrency decimal(10,2))
FxRate:
create table FxRate(
RateDate datetime,
SourceCurrency varchar(3),
TargetCurrency varchar(3),
ExchangeRate decimal(15,4))
这就是我想要做的:
我想更新我的 Bill 表,因为
update Bill
set ReportingCurrency = FxRate.ExchangeRate * Bill.Amount
from FxRate
where FxRate.RateDate = Bill.BillDate
在此更新所有包含以下条目的行:该特定日期将获得新的报告货币数据。 由于 Bill 表可以有多行符合更新条件,因此我遇到以下问题:
对于 FxRate 表(该日期)中没有条目的行,ReportingCurrency 变为 NULL。 我想返回最近的 <= RateDate
并获取汇率。是否可以使用同一更新语句中的修改或其他一些有效的方法? (我想避免光标)。
I have two tables :
Bill :
create table Bill(
BillDate datetime,
Amount decimal(10,2) ,
BillCurrency varchar(3) ,
ReportingCurrency decimal(10,2))
FxRate :
create table FxRate(
RateDate datetime,
SourceCurrency varchar(3),
TargetCurrency varchar(3),
ExchangeRate decimal(15,4))
This is what I want to do :
I want to update my Bill table as
update Bill
set ReportingCurrency = FxRate.ExchangeRate * Bill.Amount
from FxRate
where FxRate.RateDate = Bill.BillDate
In this update all the rows which have an entry for that particular date will get the new reportingcurrency data. Since Bill table can have multiple rows eligible for the update , I have the following problem :
For the rows where there was no entry in FxRate table (for that date), the ReportingCurrency becomes NULL. I want to go back to the nearest <= RateDate
and pick up the exchange rate.Is that possible using modifications in the same update statement or some other efficient method? (I want to avoid a cursor).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该能够通过子查询来实现这一点。 希望我下面的示例无需修改即可运行(并且不会出现错误!)唯一的注意事项是您需要用您的报告(基础)货币替换我假设的“美元”。
希望这可以帮助。 编辑 - 添加 ORDER BY 子句
You should be able to achieve this with a subquery. Hopefully my example below will work unmodified (and be error free!) The only note is you need to substitute your reporting (base) currency for my assumed 'USD'.
Hope this helps. EDIT - Added ORDER BY Clause
当然这是可能的 - 作为 SELECT,这将是:
因此,作为更新:
解决方案做出以下假设:
FxRate
记录,早于所有
记录Bill
记录的 FxRate如果这些假设不适用,则必须适应查询。
另请注意,这是 SQL Server 语法。 Sybase 可能有点不同。
由于评论者对一般的“最近日期”解决方案表现出兴趣:
不过,这会很慢。 选择:
Of course this is possible - as a SELECT this would be:
Therefore, as an UPDATE:
The solution makes these assumptions:
FxRate
record for any given dayFxRate
record that predates allBill
recordsIf these assumptions are not applicable, the query must be accommodated.
Also note that this is SQL Server syntax. It's possible that Sybase is a little different.
Since a commenter showed interest in a general "nearest date" solution:
This would be quite slow, though. Alternative: