Contoh Sederhana Menggunakan Cursor

Contoh Sederhana Menggunakan Cursor pada Transact-SQL

CREATE TABLE [dbo].[Kelas](
[PKKelas] [int] IDENTITY(1,1) NOT NULL,
[NamaKelas] [nchar](2) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
CONSTRAINT [PK_Kelas] PRIMARY KEY CLUSTERED
( [PKKelas] ASC ) WITH (PAD_INDEX  = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

Insert beberapa data

INSERT INTO [Kelas] ([NamaKelas]) VALUES ('1A')
INSERT INTO [Kelas] ([NamaKelas]) VALUES ('1B')
INSERT INTO [Kelas] ([NamaKelas]) VALUES ('1C')
INSERT INTO [Kelas] ([NamaKelas]) VALUES ('1D')
INSERT INTO [Kelas] ([NamaKelas]) VALUES ('1E')
INSERT INTO [Kelas] ([NamaKelas]) VALUES ('1F')
INSERT INTO [Kelas] ([NamaKelas]) VALUES ('2A')
INSERT INTO [Kelas] ([NamaKelas]) VALUES ('2B')
INSERT INTO [Kelas] ([NamaKelas]) VALUES ('2C')
INSERT INTO [Kelas] ([NamaKelas]) VALUES ('2D')
INSERT INTO [Kelas] ([NamaKelas]) VALUES ('2E')
INSERT INTO [Kelas] ([NamaKelas]) VALUES ('2F')
INSERT INTO [Kelas] ([NamaKelas]) VALUES ('3A')
INSERT INTO [Kelas] ([NamaKelas]) VALUES ('3B')
INSERT INTO [Kelas] ([NamaKelas]) VALUES ('3C')
INSERT INTO [Kelas] ([NamaKelas]) VALUES ('3D')
INSERT INTO [Kelas] ([NamaKelas]) VALUES ('3E')
INSERT INTO [Kelas] ([NamaKelas]) VALUES ('3F')

Script T-SQL

declare @GetPKKelas as cursor,
@PKKelas as int
set @GetPKKelas = cursor for
select PKKelas from Kelas

-- Loop each Kelas
open @GetPKKelas
fetch next from @GetPKKelas into @PKKelas
while @@fetch_status=0
begin
print @PKKelas
fetch next from @GetPKKelas into @PKKelas
end
close @GetPKKelas
deallocate @GetPKKelas

Tagged with: , ,
Posted in CodeLog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: