Recorrer una tabla fila por fila - MSSQLSERVER

Para poder recorrer una tabla lo mas común es usar cursores, pero hay otras formas de hacerlo como ya mostrare mas adelante.

Primero necesitamos una tabla con cual trabajar aquí un script de una simple tabla:
  1. CREATE TABLE [Region](   
  2. [RegionID] [INTNOT NULL,  
  3. [RegionDescription] [NCHAR](50) NOT NULL  
  4. )  
Insertamos algunos registros
  1. INSERT INTO [Region](  
  2. [RegionID],  
  3. [RegionDescription]  
  4. )  
  5. SELECT 1,'Eastern' UNION ALL  
  6. SELECT 2,'Western' UNION ALL  
  7. SELECT 3,'Northern' UNION ALL  
  8. SELECT 4,'Southern'  
El script del cursor seria el siguiente:
  1. DECLARE @RegionID INT,  
  2. @RegionDescription NCHAR(50)  
  3.   
  4. DECLARE my_cursor CURSOR FAST_FORWARD READ_ONLY   
  5. FOR  
  6. SELECT RegionID,  
  7. RegionDescription  
  8. FROM   Region WITH(NOLOCK)  
  9. OPEN my_cursor  
  10.   
  11. FETCH FROM my_cursor INTO @RegionID, @RegionDescription  
  12.   
  13. WHILE @@FETCH_STATUS = 0  
  14. BEGIN  
  15. -------  
  16. SELECT @RegionID,  
  17. @RegionDescription  
  18. -------   
  19. FETCH FROM my_cursor INTO @RegionID, @RegionDescription  
  20. END  
  21.   
  22. CLOSE my_cursor  
  23. DEALLOCATE my_cursor  
Usar cursores tiene sus desventajas, ya que bloquea la tabla, usan mucha memoria y son lentos. Una alternativa a estos podría ser el siguiente script que simula el funcionamiento de un cursor apoyándose en unas variables de control y un simple bucle:
  1. DECLARE @iReturnCode        INT,  
  2. @iNextRowId         INT,  
  3. @iCurrentRowId      INT,  
  4. @iLoopControl       INT,  
  5. @RegionID           INT,  
  6. @RegionDescription  NCHAR(50)  
  7.   
  8. SET NOCOUNT ON     
  9. SELECT @iLoopControl = 1  
  10. SELECT @iNextRowId = MIN(r.RegionID)  
  11. FROM   Region r WITH(NOLOCK)  
  12.   
  13. IF ISNULL(@iNextRowId, 0) = 0  
  14. BEGIN  
  15. RETURN  
  16. END  
  17.   
  18. SELECT @iCurrentRowId = r.RegionID,  
  19. @RegionID = r.RegionID,  
  20. @RegionDescription = r.RegionDescription  
  21. FROM   Region r WITH(NOLOCK)  
  22. WHERE  r.RegionID = @iNextRowId  
  23.   
  24. WHILE @iLoopControl = 1  
  25. BEGIN  
  26. SELECT @iNextRowId = NULL  
  27. SELECT @iNextRowId = MIN(r.RegionID)  
  28. FROM   Region r WITH(NOLOCK)  
  29. WHERE  r.RegionID > @iCurrentRowId   
  30. -------  
  31. SELECT @RegionID,  
  32. @RegionDescription  
  33. -------   
  34. IF ISNULL(@iNextRowId, 0) = 0  
  35. BEGIN  
  36. BREAK  
  37. END  
  38.   
  39. SELECT @iCurrentRowId = r.RegionID,  
  40. @RegionID = r.RegionID,  
  41. @RegionDescription = r.RegionDescription  
  42. FROM   Region r WITH(NOLOCK)  
  43. WHERE  r.RegionID = @iNextRowId  
  44. END  

0 comentarios:

Publicar un comentario