Aqui estão pontos importantes a serem lembrados sobre o KEYSET Cursor no SQL Server
- Se sua consulta Select estiver usando qualquer tabela sem índice exclusivo, o cursor KEYSET será simplesmente convertido em cursor estático. Certifique-se de que todas as tabelas que você está usando em Select Query tenham um índice exclusivo. Isso é importante, pois o KEYSET Cursor cria identificadores exclusivos para as linhas usando esses valores exclusivos.
- Se inserirmos as linhas na(s) tabela(s) de origem quando o cursor estiver aberto. Essas inserções não serão visíveis no cursor já aberto.
- Se atualizarmos valores não-chave nas tabelas base, essas alterações ficarão visíveis no cursor.
- Se você atualizar o valor da coluna Chave na(s) Tabela(s) Base enquanto o cursor estiver aberto e tentar buscar o valor. @@FETCH_STATUS retornará -2. A atualização feita dentro do cursor para Key Column com a cláusula WHERE CURRENT OF ficará visível no final do Cursor.
- Se você excluir a linha da(s) Tabela(s) Base enquanto o cursor estiver aberto e tentar buscar essa linha no cursor, @@FETCH_STATUS retornará -2.
- Os cursores KEYSET são roláveis.
Create table dbo.Customer (
CustomerId Int ,
CustomerName VARCHAR(100),
StreetAddress VARCHAr(100),
City VARCHAR(100),
State CHAR(2))
go
--Create Unique Index on CustomerID
CREATE UNIQUE INDEX UQ_CustomerID
ON dbo.Customer (CustomerID);
--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'
--Insert NEW Record
Insert into dbo.Customer
Select 5,'Robert Ladson','Pathway Street Address','High Point','NC'
--Delete Records
Delete from dbo.Customer
Where CustomerID in (3,4)
--Update All Record for NONKEY Column
Update dbo.Customer
set CustomerName='NO NAME'
--Update Key Column value
Update dbo.customer
set CustomerID=9
where Customerid=3
--KEYSET CURSOR Script
Declare @CustomerID INT
Declare @CustomerNAme VARCHAR (100)
DECLARE @StreetAddress VARCHAR(100)
DECLARE @City VARCHAR(100)
DECLARE @State CHAR(2)
--DECLARE A CURSOR
DECLARE CUR CURSOR
KEYSET
FOR
Select CustomerID,CustomerName,StreetAddress,City,State from dbo.Customer
--OPEN CURSOR
OPEN CUR
Print 'CURSOR IS OPEN'
--FETCH NEXT RECORD
FETCH NEXT FROM CUR INTO @CustomerID,@CustomerNAme,@StreetAddress,@City,@State
WHILE @@FETCH_STATUS=0
BEGIN
RAISERROR ('',0,1) WITH NOWAIT
WAITFOR DELAY '00:00:15'
--You can use CONCAT Function in SQL 2012 AND Latest for Contatenation of Integters and Strings
--PRINT CONCAT(@CustomerID,' ',@CustomerNAme,' ',@StreetAddress,' ',@City,' ',@State)
Print CAST(@CustomerID AS VARCHAR(10))+' '+@CustomerNAme+' '+@StreetAddress+' '+@City+' '+@State
FETCH NEXT FROM CUR INTO @CustomerID,@CustomerNAme,@StreetAddress,@City,@State
Print @@FETCH_STATUS
END
CLOSE CUR
DEALLOCATE CUR Demonstração em vídeo:o que são cursores KEYSET no SQL Server e como funciona o cursor KEYSET