【发布时间】:2015-12-25 18:37:49
【问题描述】:
我有一些代码用于在表中插入值,用 SQL Server 编写:
创建表/构建架构:
CREATE TABLE Inter
([id] int, [MarkDate] date, [MaturityDate] date, [ZeroRate] int)
;
INSERT INTO Inter
([id], [MarkDate], [MaturityDate], [ZeroRate])
VALUES
(1, '2015-07-02', '2015-07-02', 1),
(2, '2015-07-02', '2015-07-03', 5),
(3, '2015-07-02', '2015-07-06', 15)
;
CREATE TABLE allDates
([id] int, [MaturityDate] date)
;
INSERT INTO allDates
([id], [MaturityDate])
VALUES
(1, '2015-07-01'),
(2, '2015-07-02'),
(3, '2015-07-03'),
(4, '2015-07-04'),
(5, '2015-07-05'),
(6, '2015-07-06'),
(7, '2015-07-07'),
(8, '2015-07-08'),
(9, '2015-07-09')
;
CREATE TABLE rangesInter
([id] int, [MarkDate] date, [begindate] date, [enddate] date, startRate float, rateChange float);
INSERT INTO rangesInter
SELECT
I1.id,
I1.[MarkDate],
I1.[MaturityDate] begindate,
I2.[MaturityDate] enddate,
I1.[ZeroRate] startRate,
(I2.ZeroRate - I1.ZeroRate) * 1.0 / DATEDIFF ( day , I1.[MaturityDate], I2.[MaturityDate] ) rateChange
FROM Inter I1
inner join Inter I2
on I1.id = I2.id - 1;
插值:
SELECT
IIF(i.MarkDate IS NULL, r.MarkDate, i.MarkDate) as MarkDate,
a.MaturityDate,
IIF(i.ZeroRate IS NULL,
r.startRate + DATEDIFF ( day , r.begindate, a.MaturityDate ) * rateChange,
i.ZeroRate) as ZeroRate,
i.*, r.*
FROM
allDates a
LEFT JOIN
Inter I ON a.MaturityDate = I.MaturityDate
CROSS JOIN
(SELECT
MIN(MaturityDate) minDate, MAX(MaturityDate) maxDate
FROM Inter) AS t
LEFT JOIN
(SELECT
I1.id, I1.[MarkDate],
I1.[MaturityDate] begindate, I2.[MaturityDate] enddate,
I1.[ZeroRate] startRate,
(I2.ZeroRate - I1.ZeroRate) * 1.0 / DATEDIFF ( day , I1.[MaturityDate], I2.[MaturityDate] ) rateChange
FROM
Inter I1
INNER JOIN
Inter I2 ON I1.id = I2.id - 1) r ON a.MaturityDate > r.[begindate]
AND a.MaturityDate < r.[enddate]
WHERE
a.MaturityDate >= t.minDate
AND a.MaturityDate <= t.maxDate;
如何将此代码转换为 MS Access VBA?
我不确定如何开始转换代码的“插值”部分以使用 Access VBA。
【问题讨论】:
-
在我看来是合法的。您是否真的尝试在 Access 中运行该代码?它有没有给你任何具体的错误?如果有的话,我认为反过来也行不通。我认为您需要 CASE WHEN 语句而不是 SQL Server 中的 IIF。
-
在 VBA 中编写代码时,您会发现此答案中概述的技术可帮助您简化在 VBA 中构建的 SQL 字符串,请参阅:stackoverflow.com/questions/31684546/…
标签: sql sql-server sql-server-2008 ms-access vba