Membuat TRIGGER pada database MySQL


Ada tugas nih membuat trigger, tanya mbah google di beritahu contoh ini. Tak simpan aja sebagai catatanku hari ini.

Trigger merupakan suatu prosedur yang otomatis akan dijalankan apabila “pemicu” dari trigger itu dipanggil. Sebagai contoh: penghapusan satu tabel akan memicu suatu trigger untuk menghapus pada tabel yang lain yang telah ditunjuk terlebih dahulu. dibawah ini saya berikan satu contoh penggunaan trigger pada database MySQL.

Sebagai contoh kita siapkan terlebih dahulu sebuah database dan tabel yang akan diuji coba seperti dibawah ini:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
create database mytrigger;

create table coba (
kode varchar(5) not null,nama varchar(35) not null,
primary key (kode))

create table coba2 (
kode varchar(5) not null,nama varchar(35) not null,
primary key (kode))

create table tran (
kode varchar(5) not null,
kodetran varchar(5),jumlah double,
primary key nkode (kode,kodetran))

Kemudian buatlah sebuah trigger dengan kode seperti dibawah ini:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
delimiter $$

create trigger auto_insert_coba2
before insert on coba for each row
begin
  insert into coba2 (kode,nama) values (NEW.kode,NEW.nama);
end$$

create trigger auto_update_coba2
before update on coba for each row
begin
  update coba2 set nama=NEW.nama where kode=NEW.kode;
end$$

create trigger auto_delete_coba2
before delete on coba for each row
begin
delete from coba2 where kode=OLD.kode;
delete from tran where kode=OLD.kode;
end$$

pada trigger di atas setiap kali perubahan dilakukan terhadap tabel COBA maka secara otomatis
tabel COBA2 akan dipengaruhi / terpengaruh.

Sumber. Arianto

Tinggalkan Balasan

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 / Ubah )

Twitter picture

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

Facebook photo

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

Connecting to %s

Ikuti

Get every new post delivered to your Inbox.