sqlserver数据库,查询某条记录的上一条,修改并保持

一、表结构:
CREATE TABLE [dbo].DB1dBar
注意:前一个交易日不一定是 rDate-1日,例如周末股市不开市。
二、需求:假设DB1dBa中pre__close=0的所有行为A,将A每一条记录的前一个交易日rClose赋值给A,并更新数据库。
三、要求:给出测试正确的demo
四、参考:
1、给日期加序号:select code, rDate,rClose,ROW_NUMBER() over(partition by code order by rDate desc
2、是否考虑使用 with as 以增强代码可维护性

preclose字段我取消掉下划线,下同
首先你要确定几个问题:preclose字段一旦为0,即更新为上一次日期除却preclose的记录,还是只有当你查询到preclose为0,才更新为上一次日期记录?
另外,preclose是否重改?每次插入的记录是否单条?这几个问题确定下来,才能采取最有效的方法。
如果preclose不复改且为0时更新、每次插入单条记录,那用触发器就行了:
create trigger ... on DB1dBar instead of insert as
insert into DB1dBar select rDate,code,(select top 1 rClose from DB1dBar where rDate < sd.rDate order by rDate desc),preclose from inserted sd where sd.preclose=0
如果不是,比如几条记录是同时插入的,甚至日期不同的记录同时插入,或者等用户有需要才进行更新:
declare @i date
declare cr cursor FAST_FORWARD local for select rDate from DB1dBar where preclose=0 and rDate between 起始日期 and 终止日期
open cr
fetch from cr into @i
while(@@FETCH_STATUS=0)
begin
update DB1dBar set rClose=(select top 1 rClose from DB1dBar where rDate<@i order by rDate desc) where rDate=@i and preclose=0
fetch from cr into @i
end
close cr
deallocate cr

如有数据重改的情况,类同,但须记录此前的rClose

一、表结构:
CREATE TABLE [dbo].DB1dBar

rDate date NOT NULL,    --日期
code int NOT NULL,      -- 股票代码
rClose int NOT NULL,    --rDate日收盘价
pre_close int NOT NULL -- rDate日前一个交易日的收盘价

一、表结构:
DB1dBar
rDate date NOT NULL, --日期
code int NOT NULL, -- 股票代码
rClose int NOT NULL, --rDate日收盘价
pre_close int NOT NULL -- rDate日前一个交易日的收盘价

update DB1dBar set DB1dBar.pre_close = b.rClose
FROM DB1dBar A JOIN (select code,case when datepart(week,dateadd(day,-1,rDate) ) = 7 then dateadd(day,-2,rDate) else dateadd(day,-1,rDate) end rDate ,rClose from DB1dBar) B
ON A.code = B.code and A.rDate =B.rDate

因为没有sqlserver环境,就手敲的。也不知道正不正确。你可以试试。