我有一个包含“余额”列的表格,其中存储了每个客户帐户(Account_id)的最新余额。现在我想自动增加对年度余额的兴趣,并且在完成每一年后,应该在新的余额中添加利息。我怎么能用VB.Net(Visual Studio 2008)和Sql Server(Express版本)做到这一点?
表名是Deposit。列是这样的:
Trans_id Acc_id Trans_date 金额 余额
答案 0 :(得分:0)
我相信这是你正在寻找的。我不得不在帐户表中添加一个列,我假设有一个客户表,其中包含"出生日期"。
declare @customer table(
[acc_id] [int] identity(1, 1)
, [name] [sysname]
, [created] [datetime] default dateadd(year, -1, current_timestamp));
insert into @customer
([name])
values (N'joe'),
(N'sally');
--
declare @account table (
[trans_id] [int] identity(1, 1)
, [acc_id] [int]
, [trans_date] [datetime] default current_timestamp
, [amount balance] [money]
, [interest_paid] [datetime] null);
insert into @account
([acc_id],[amount balance])
values (1,N'25.00'),
(2,N'50.00');
--
declare @interest [float] = 0.03;
update @account
set [amount balance] = [amount balance] + ( [amount balance] * @interest )
, [interest_paid] = current_timestamp
from @account as [account]
join @customer as [customer]
on [customer].[acc_id] = [account].[acc_id]
where ( datediff(day
, [interest_paid]
, current_timestamp) >= 365
or [interest_paid] is null )
and datediff(day
, [customer].[created]
, current_timestamp) >= 365;
--
select * from @account as [account]
join @customer as [customer]
on [customer].[acc_id] = [account].[acc_id];
--
-- this should not update as the [interest_paid] date is less than one year old
update @account
set [amount balance] = [amount balance] + ( [amount balance] * @interest )
, [interest_paid] = current_timestamp
from @account as [account]
join @customer as [customer]
on [customer].[acc_id] = [account].[acc_id]
where ( datediff(day
, [interest_paid]
, current_timestamp) >= 365
or [interest_paid] is null )
and datediff(day
, [customer].[created]
, current_timestamp) >= 365;
--
select *
from @account as [account]
join @customer as [customer]
on [customer].[acc_id] = [account].[acc_id];
--
declare @future [datetime] = dateadd(year
, 1
, current_timestamp);
--
-- this SHOULD update as the [interest_paid] date is a year old based on the future date
update @account
set [amount balance] = [amount balance] + ( [amount balance] * @interest )
, [interest_paid] = @future
from @account as [account]
join @customer as [customer]
on [customer].[acc_id] = [account].[acc_id]
where ( datediff(day
, [interest_paid]
, @future) >= 365
or [interest_paid] is null )
and datediff(day
, [customer].[created]
, @future) >= 365;
--
select *
from @account as [account]
join @customer as [customer]
on [customer].[acc_id] = [account].[acc_id];