日期:2014-05-18  浏览次数:20576 次

求一逐行更新语句
create table #aa(
fid int,
fbeg int,
fin int,
fout int,
fend int)

insert into #aa values(1,1,2,3,0)
insert into #aa values(2,1,8,0,0)
insert into #aa values(3,1,0,7,0)

现在要更新fend这一列,使第二行的fend=第一行的fend+第二行的fin-第二行的out,得到如下结果

1 1 2 3 0
2 1 8 0 8
3 1 0 7 1

------解决方案--------------------
用游标好了
------解决方案--------------------
--和此例类似,请参考.
SQL code
SQLServer语法(要求不使用游标) 
单表T
字段  a(int)  b(int)  c(int)  d(int)
    1    0    0    10
    2    10    5    Null
    3    20    10    Null
    4    30    15    Null
a字段自增,所需结果如下
字段  a(int)  b(int)  c(int)  d(int)
    1    0    0    10
    2    10    5    15
    3    20    10    25
    4    30    15    40
过程 根据a自增, 累加d(初始为10)  d=d+(b-c)


单语句Update如何写

if object_id('tempdb..#tmp') is not null
  drop table #tmp
GO

create table #tmp(a int,b int,c int , d int)
insert #tmp
select 1,0 ,0 ,10 union all
select 2,10,5 ,null union all
select 3,20,10,null union all
select 4,30,15,null

update #tmp
set d=(select isnull(sum(b-c),0)
from #tmp TT
where TT.a <=#tmp.a)+(select d from #tmp where a=1)

select * from #tmp

drop table #tmp

a      b      c      d     
----------- ----------- ----------- -----------
1      0      0      10
2      10      5      15
3      20      10      25
4      30      15      40

(所影响的行数为 4 行)


有表
商品    收入    发出    结存
月初数              10
a      5      0     
b      0      2

如何用update 语句更新结存数,结存数为上一行的结存+本行的收入-本行的发出
如上表中a的结存为15,b的结存为13
要求:不用游标,尽量不用循环,只用一句话

if object_id('pubs..tb') is not null
drop table tb
go

create table tb
(
商品 varchar(10),
收入 int,
发出 int,
结存 int
)

insert into tb(商品,收入,发出,结存) values('月初数',null,null,10)
insert into tb(商品,收入,发出,结存) values('a',5,0,0)
insert into tb(商品,收入,发出,结存) values('b',0,2,0)

update tb
set 结存=(select isnull(sum(收入-发出),0)
from tb tt
where tt.商品 <=tb.商品 and tb.商品 <>'月初数')+(select 结存 from tb where 商品='月初数')

select * from tb
drop table tb

商品    收入    发出    结存     
---------- ----------- ----------- -----------
月初数  NULL    NULL    10
a      5      0      15
b      0      2      13

(所影响的行数为 3 行)

------解决方案--------------------
SQL code

create table #aa( fi