급여 관리 시스템 트리거

트리거

: 테이블에 대한 이벤트에 반응해 자동으로 실행되는 작업

트리거 구조

delimiter // -- 트리거 안에 세미콜론이 있음
	create trigger trigger_name
	before update on table_name
	for each row -- 업데이트를 행단위로 하고 있음. 업데이트되는 각 행을 실행
	begin
		# code
	end
//

sql 수정 삭제 가능하도록 설정

set sql_safe_updates = 0;

DB 생성 및 초기화

drop database if exists trigger_demo; -- 스키마 중복 시 삭제
create SCHEMA `trigger_demo` ; -- 스키마 생성
use trigger_demo;

직원 테이블 생성

-- 직원 테이블 생성
create table employees(
	id int auto_increment primary key,
    name varchar(100) not null,
    salary decimal(10,2) not null, -- 소수점 두자리까지 지원
    department varchar(50) not null,
    created_at timestamp default current_timestamp -- 데이터 생성 시간
);

급여 변경 이력 테이블

; 기존 데이터와 섞이는 것을 방지하기 위해 생성.

→ 외래키를 참조해서 테이블 생성 (직원 테이블이랑 엮음)

create table salary_logs(
	id int auto_increment primary key,
    employee_id int, -- employees 테이블의 id 참조
	old_salary decimal(10,2),
    new_salary decimal(10,2),
    change_date timestamp default current_timestamp,
    -- foreign key는 참조를 했을 경우 써주는 것이 좋음 -> 데이터 무결성 유지
    foreign key (employee_id) references employees(id) on delete cascade -- 해당 직원 삭제 시 연쇄적으로 삭제
);