sql >> Base de Datos >  >> RDS >> Sqlserver

Tipos de cursor de SQL Server:¿Cuál es la diferencia entre el cursor LOCAL Y GLOBAL? Tutorial de SQL Server / Tutorial de TSQL

Cursor local:

El alcance de Local Cursor se limita al lote, procedimiento almacenado o activador en el que se crea. Una vez que se completa el lote, el procedimiento almacenado o el disparador. El cursor local ya no estará disponible para su uso.

CURSOR GLOBAL:

El alcance de GLOBAL Cursor se limita a la conexión en la que se crea. Puede usar el CURSOR GLOBAL en varios lotes, puede abrir primero y obtener los datos en segundo lugar. También puede abrir el CURSOR GLOBAL en un procedimiento almacenado y obtener los datos en el siguiente procedimiento almacenado, siempre que utilicen la misma conexión.
Si no usaría la palabra clave Local o Global, el Cursor se creará con TYPE utilizando la configuración de la base de datos como se muestra a continuación.
Fig. 1:diferencia entre el cursor local y el cursor global en SQL Server
Vamos a crear una tabla de muestra e inserte algunos registros y haga algunas pruebas para probar nuestra definición anterior.

--drop table dbo.Customer
Create table dbo.Customer ( 
CustomerId Int ,
CustomerName VARCHAR(100),
StreetAddress VARCHAr(100),
City VARCHAR(100),
State CHAR(2))
go

--Insert few Records in Sample Table
Insert into dbo.Customer
Select 1,'Aamir shahzad','Test Street Address','Charlotte','NC'
Union all
Select 2,'M Raza','Test Street Address','Charlotte','NC'
union all
Select 3,'John Smith','Test Street Address','New York City','NY'
union All
Select 4,'Christy Richard','Test Street Address','Rio Rancho','NM'




--Test with GLOBAL Cursor in Multiple Batches. 
use Test
go

DECLARE Customer_Cursor CURSOR 
--use LOCAL OR GLOBAL HERE
GLOBAL 
FOR
Select CustomerID,
CustomerName,
StreetAddress,
City,
State
from dbo.Customer
OPEN Customer_Cursor;
GO

--Terminate the Batch and change the Database 
use TestDB
go
FETCH NEXT FROM Customer_Cursor
WHILE (@@FETCH_STATUS <> -1)
BEGIN
   FETCH NEXT FROM Customer_Cursor 
   END
CLOSE Customer_Cursor;
GO
DEALLOCATE Customer_Cursor;
GO

We will be able to see the records as we have defined Cursor as GLOBAL and it will be 
available during entire Connection , even we have terminated the first Batch by using GO
statement.


Fig 2: Global Cursor in SQL Server
--Test with LOCAL Cursor in Multiple Batches. 
use Test
go

DECLARE Customer_Cursor CURSOR 
--use LOCAL OR GLOBAL HERE
LOCAL 
FOR
Select CustomerID,
CustomerName,
StreetAddress,
City,
State
from dbo.Customer
OPEN Customer_Cursor;
GO

--Terminate the Batch and change the Database 
use TestDB
go
FETCH NEXT FROM Customer_Cursor
WHILE (@@FETCH_STATUS <> -1)
BEGIN
   FETCH NEXT FROM Customer_Cursor 
   END
CLOSE Customer_Cursor;
GO
DEALLOCATE Customer_Cursor;
GO
 
 
As the scope for LOCAL Cursor is limited to Batch, Stored Procedure or Trigger, The second batch is not able to see the Cursor as we have defined LOCAL Cursor type in our above query
Figura 3:Cursor local en SQL Server
 

Ahora realicemos la prueba con el procedimiento almacenado y veamos cómo funcionan el cursor local y el cursor global en el procedimiento almacenado en SQL Server.
--Test with LOCAL Cursor in Multiple Batches. 
use Test
go

Create Procedure Dec_Cursor_Customer AS
BEGIN
DECLARE Customer_Cursor CURSOR 
--use LOCAL OR GLOBAL HERE
GLOBAL 
FOR
Select CustomerID,
CustomerName,
StreetAddress,
City,
State
from dbo.Customer
OPEN Customer_Cursor;
END

GO
Create Procedure Fetch_Cusor_Customer
AS 
BEGIN
FETCH NEXT FROM Customer_Cursor
WHILE (@@FETCH_STATUS <> -1)
BEGIN
   FETCH NEXT FROM Customer_Cursor 
   END
END

--Execute the Procedures to What we get with GLOBAL and LOCAL Cursor Type

EXEC Dec_Cursor_Customer
GO
EXEC Fetch_Cusor_Customer
CLOSE Customer_Cursor;
GO
DEALLOCATE Customer_Cursor;
GO
 
 
Si ejecutamos el procedimiento almacenado anterior, obtendremos los resultados que obtuvimos en la figura 2. Como hemos declarado como tipo GLOBAL, podremos usarlo en varios procedimientos almacenados siempre que los ejecute en misma conexión.

Adelante, modifique el procedimiento almacenado y cambie el tipo de GLOBAL a Local y luego ejecute los procedimientos. Incluso si estamos en la misma conexión, obtendremos el error que obtuvimos en la Fig. 3. Como el alcance del Cursor se limita a Lote, Procedimiento almacenado o Activador una vez que se define como LOCAL.
Demostración en video:para ver la demostración detallada de cómo funciona el cursor local y el cursor global, mire el video.