sol1dphp

Example_Cursor_TSQL_W_WHILE

Dec 10th, 2013
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.08 KB | None | 0 0
  1. declare @tabela as table (obraid int, cronograma int, mes int, ano int)
  2. declare @teste as table (obraid int, cronograma int, mes int, ano int)
  3. insert into @tabela values(123,5,08,2013)
  4. insert into @tabela values(124,4,09,2013)
  5. insert into @tabela values(125,4,12,2013)
  6.  
  7. declare @cronograma int,
  8. @obraid int ,
  9. @mes int,
  10. @ano int,
  11. @mesAlterado int,
  12. @Rownu int
  13.  
  14. set @Rownu = 0
  15.  
  16. DECLARE cursor_objects CURSOR FOR
  17.     select obraid,cronograma,mes,ano
  18. from @tabela
  19.  
  20. OPEN cursor_objects
  21. FETCH NEXT FROM cursor_objects INTO @obraid,@cronograma,@mes,@ano
  22.  
  23. WHILE @@FETCH_STATUS = 0
  24. BEGIN
  25. while @cronograma > 0
  26. begin
  27.  
  28.  
  29. set @Rownu = @Rownu + 1
  30.  
  31. if @Rownu =  1  set @mesAlterado = @mes
  32.  
  33. if @Rownu > 1
  34.  
  35. set @mesAlterado =  @mes +1
  36.  
  37. insert into @teste (obraid,cronograma,mes,ano ) values (@obraid,@Rownu,@mesAlterado, @ano)
  38.  
  39. set @cronograma = @cronograma  - 1
  40.  
  41. set @mes = @mesAlterado
  42.  
  43.  
  44.  
  45. end
  46. FETCH NEXT FROM cursor_objects INTO @obraid,@cronograma,@mes,@ano
  47. END
  48.  
  49. CLOSE cursor_objects
  50.  
  51.  
  52. DEALLOCATE cursor_objects
  53.  
  54.  
  55. select * from @teste
Advertisement
Add Comment
Please, Sign In to add comment