Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

Jenis Kursor SQL Server - Hanya Meneruskan Kursor Dinamis | Tutorial SQL Server / Tutorial TSQL

kursor adalah objek yang memungkinkan kita mengakses data baris demi baris dari kumpulan hasil.

Forward Only Cursors tidak mengizinkan pengguliran mundur. Satu-satunya opsi pengguliran yang kami miliki adalah FETCH NEXT.

Forward only Static Cursors sensitif terhadap setiap perubahan ( update, delete, insert) yang dilakukan pada sumber data asli. Jika dilakukan perubahan, perubahan tersebut akan diekstrak pada Next Fetch.


Script for Forward_Only Dynamic Cursor


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

--Insert couple of Records in Sample Table
Insert into dbo.Customer
Select 'Aamir shahzad','Test Street Address','Charlotte','NC'
Union 
Select 'M Raza','Test Street Address','Charlotte','NC'

Select * from dbo.Customer

--Insert NEW Record
Insert into dbo.Customer
Select 'John Smith','Test Street Address','New York City','NY'

--Delete Records
Delete from dbo.Customer
Where CustomerName in ('Aamir Shahzad','M Raza')

--Update All Record
Update dbo.Customer
set CustomerName='NO NAME'




--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
Forward_Only Dynamic
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'
PRINT CONCAT(@CustomerID,' ',@CustomerNAme,' ',@StreetAddress,' ',@City,' ',@State)
FETCH NEXT FROM CUR INTO @CustomerID,@CustomerNAme,@StreetAddress,@City,@State

END
CLOSE CUR
DEALLOCATE CUR



Tonton video Forward Only Dynamic Cursor detail di SQL Server


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Kinerja SQL Server IN vs. EXISTS

  2. Bagaimana cara mengganti string di Kolom Tabel SQL Server

  3. SQL Server menambahkan kunci utama kenaikan otomatis ke tabel yang ada

  4. Format sysjobhistory datetime &durasi Kolom di SQL Server

  5. Hasilkan Tanggal antara rentang tanggal