sql游标来循环一个列并确定一个序列的范围

fcy6dtqo  于 2021-06-18  发布在  Mysql
关注(0)|答案(0)|浏览(327)

我正在尝试设置一个游标来循环遍历表中的一列,并确定序列是否已结束。如果序列已经结束,我想输出start和end值。例如:

  1. 00001
  2. 00002
  3. 00003
  4. 00004 -- End here and output 1-4
  5. 00007
  6. 00008
  7. 00009 -- End here and output 7-9
  8. 00011
  9. 00012
  10. 00013 -- End here and output 11-13

我对游标非常陌生,但我相信这就是你开始处理它们的方式:

  1. DECLARE @Product bigint
  2. DECLARE @ProductId nvarchar(100)
  3. DECLARE @ProductCursor CURSOR
  4. SET @ProductCursor = CURSOR FOR
  5. SELECT
  6. Products.Product,
  7. Products.ProductId
  8. FROM Products
  9. OPEN @ProductCursor
  10. FETCH NEXT FROM @ProductCursor INTO
  11. @Product,
  12. @ProductId
  13. WHILE @@FETCH_STATUS = 0
  14. BEGIN
  15. --Do something
  16. SELECT 'aaa'
  17. FETCH NEXT FROM @ProductCursor INTO
  18. @Product,
  19. @ProductId
  20. END
  21. CLOSE @ProductCursor
  22. DEALLOCATE @ProductCursor

我的想法是,我应该循环遍历从1到13的值,并检查它之前的值是否等于当前值。这样,如果我们在0004上,我们应该在变量中保持上一个值(00003),加1并检查它是否等于当前值(00004)。如果没有,我们就必须结束当前序列并输出起始值和结束值。我不太清楚这是怎么做的,也许要设立一个柜台?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题