欢迎投稿

今日深度:

sql中循环处理当前行数据和上一行数据相加减,

sql中循环处理当前行数据和上一行数据相加减,sql一行


  以下事例,使用游标循环表#temptable中数据,然后让当前行和上一行中的argument1 相加 存放到当前行的 argument2 中,比较简单。

--drop table #temptable
create table #temptable
(
  argument1 int,
  argument2 int,
  argument3 datetime
)

declare @rowcount int,@argument1 int,@argument2 nvarchar(50),@argument3 datetime
set @rowcount=1
set @argument1=1
set @argument2=0
set @argument3=GETDATE()

while(@rowcount<100)
begin
  insert into #temptable(argument1,argument2,argument3)
        values(@argument1,@argument2,@argument3)
  
  set @argument1=@argument1 + datepart(day,@argument3)
  set @argument3=@argument3-1  
  set @rowcount = @rowcount + 1
end

--select * from #temptable

declare @lastargument2 int
set @lastargument2=0
set @argument2=0
declare _cursor cursor for(select argument1 from #temptable)
open _cursor;
fetch next from _cursor into @argument2 
while @@fetch_status = 0
begin      
  update #temptable
  set argument2=@argument2+@lastargument2
  where current of _cursor
  
  set @lastargument2=@argument2  
  fetch next from _cursor into @argument2 
end
close _cursor
deallocate _cursor

--select * from #temptable

问一个问题:

第一句fetch next from _cursor into @argument2 这句为什么不能放在while循环的第一行,删除第二行呢?我记得自己当时在这里出错了,呵呵。


SQL数据库字段加减一个定量的实现语句

update table_name set PAS00000000055956 = PAS00000000055956 + '9000000' where...

前提是你的字段类型要对

那么你就把数据读出来,然后操作
如用PHP开发, 那么就可以很容易根据数据的特性来选择数据段运算.
然后再写入,我也是初学,通常我会这样处理.

不过就你的问题我有另外一个想法,就是在数据库里只存储数字部分,然后对其运算,然后在读取时候再进行判断,处理输入.

这才是程序设计的正确思路: 物理层+逻辑层+输出层.
再大型的程序分了这三层来定义,思路都能清晰起来.
 

SQL中怎写可以得到这一行减去上一行的值,循环处理多行多谢

create table biao22 ( a int)

insert biao22 select '10'

insert biao22 select '9'

insert biao22 select '20'

insert biao22 select '25'

insert biao22 select '18'

insert biao22 select '7'

select * from biao22

create table #A ( id int identity(1,1), a int)

insert into #a(a)
select * from biao22

declare @a int
declare @b int

select @a=min(id) from #a

select @b=max(id) from #a

while (@a<@b)

begin

select t1.a-t2.a from #a t1,#a t2 where t1.id=t2.id+1 and t1.id=@a

set @a=@a+1

end
 

www.htsjk.Com true http://www.htsjk.com/Sql_Server/11608.html NewsArticle sql中循环处理当前行数据和上一行数据相加减,sql一行 以下事例,使用游标循环表#temptable中数据,然后让当前行和上一行中的argument1 相加 存放到当前行的 argument2 中,比较简单。 --...
评论暂时关闭