早教吧 育儿知识 作业答案 考试题库 百科 知识分享

sql游标如下,某公司成立于2000年,逐年的销售额如下表(累计销售额指自公司成立以来的销售额):年份当年销售额累计销售额200045.23200156.982002

题目详情
sql 游标
如下,某公司成立于2000年,逐年的销售额如下表(累计销售额指自公司成立以来的销售额):
年份 当年销售额 累计销售额
2000 45.23

2001 56.98

2002 58.32

2003 40.67

2004 60.00

2005 45.05

1、 使用游标的方法,计算每年的累计销售额,并填入表中.
这样写有什么不对
declare @uppersale float
declare @totalsale float
declare xiaoshou_cursor scroll cursor
for
select nowsale,totalsale from xiaoshou
open xiaoshou_cursor
fetch Prior from xiaoshou_cursor into @uppersale,@totalsale
while(@@FETCH_STATUS=0)
begin
update xiaoshou set totalsale=nowsale+@uppersale
fetch next from xiaoshou_cursor into @uppersale,@totalsale
end
close xiaoshou_cursor
deallocate xiaoshou_cursor

希望哪位帮我看哈
▼优质解答
答案和解析
CREATE TABLE  xiaoshou (
  saleyear   int    PRIMARY  KEY,
  nowsale    decimal(6,2),
  totalsale  decimal(6,2)
);

GO

INSERT INTO xiaoshou(saleyear, nowsale)
SELECT  2000,  45.23   UNION  ALL
SELECT  2001,  56.98   UNION  ALL
SELECT  2002,  58.32   UNION  ALL
SELECT  2003,  40.67   UNION  ALL
SELECT  2004,  60.00   UNION  ALL
SELECT  2005,  45.05;

GO


BEGIN
  declare @saleyear  INT;
  declare @uppersale decimal(6,2);
  declare @totalsale decimal(6,2);
  
  SET @totalsale=0;
  
  -- 定义游标. (方向向前, 可更新, 按时间排序)
  declare xiaoshou_cursor cursor for
  select saleyear, nowsale from xiaoshou  ORDER  BY  saleyear
  FOR UPDATE;
  
  open xiaoshou_cursor;
  
  fetch NEXT from xiaoshou_cursor into @saleyear, @uppersale;
  
  while(@@FETCH_STATUS=0)
  begin 
  
    -- 递增总金额.
    SET @totalsale=@totalsale + @uppersale;
    
-- 更新数据.
    update xiaoshou set totalsale = @totalsale
WHERE
      CURRENT OF xiaoshou_cursor;

    fetch next from xiaoshou_cursor into @saleyear, @uppersale;
  end
  
  close xiaoshou_cursor
  deallocate xiaoshou_cursor
END

GO


SELECT * FROM xiaoshou
GO

saleyear    nowsale  totalsale
----------- -------- ---------
       2000    45.23     45.23
       2001    56.98    102.21
       2002    58.32    160.53
       2003    40.67    201.20
       2004    60.00    261.20
       2005    45.05    306.25

(6 行受影响)
看了 sql游标如下,某公司成立于...的网友还看了以下: