트리거(Trigger)는 특정 테이블에 INSERT, DELETE, UPDATE 같은 DML 문이 수행되었을 때, 데이터베이스에서 자동으로 동작하도록 작성된 프로그램. 사용자가 직접 호출하는 것이 아니라, 데이터베이스에서 자동적으로 호출하는 것이 가장 큰 특징.
create trigger save_history (trigger name)
after insert or update on A (table name)
-> insert와 update후에 아래의 (procedure, function)을 실행하겠다.
for each row
execute procedure trigger_upsert_data() -> (실행할 function);
function은 procedure와는 달리 return값이 항상 있어야한다.
create or replace function public.fn_test_table_insert(p_title varchar)
returns integer AS
$$
declare v_no integer := -1;
BEGIN
-- 제목의 필수사항을 확인
if p_title is null or length(p_title) = 0 then
raise notice '$1 title 필수사항';
return -1;
end if;
-- primary key : no 채번
select coalesce(max(no), 0) + 1 into v_no
from public.test_table;
insert into public.test_table
(no, title, create_date)
values
(v_no, p_title, current_timestamp);
return v_no;
END;
$$
LANGUAGE plpgsql
트랜잭션은 하나의 작업 자체를 이야기한다.
select, update 같은것을 의미하지만 하나의 select문을
이야기하는것이 아니라, select를 해서 update까지. 즉 사용자와 개발자가
원하는 하나의 작업 자체를 이야기하는것이 transaction이라고 생각할수있다.
프로시저는 일련의 쿼리를 마치 하나의 함수처럼 실행하기 위한 쿼리의 집합이며, 일련의 작업을 정리한 절차이다.