๐Ÿ’พ MySQL - Trigger

suRanยท2022๋…„ 7์›” 16์ผ
0

๐Ÿ’พ MySQL

๋ชฉ๋ก ๋ณด๊ธฐ
8/9
post-thumbnail

๋ณธ ํฌ์ŠคํŒ…์€ ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๋ฏธ๋‹ˆ ๋ฐ๋ธŒ ์ฝ”์Šค๋ฅผ ๊ณต๋ถ€ํ•˜๋ฉฐ
ํ•™์Šต์„ ๊ธฐ๋กํ•˜๊ธฐ ์œ„ํ•œ ๋ชฉ์ ์œผ๋กœ ์ž‘์„ฑ๋œ ๊ธ€์ž…๋‹ˆ๋‹ค.

Trigger๋ž€?

Trigger๋Š” ํŠน์ • ํ…Œ์ด๋ธ”์— ๋ ˆ์ฝ”๋“œ ์ถ”๊ฐ€/ ์‚ญ์ œ / ๊ฐฑ์‹  ์ž‘์—…์ด
๋ฒŒ์–ด์ง€๊ธฐ ์ง์ „์ด๋‚˜ ์งํ›„์— ์–ด๋–ค ์ž‘์—…์„ ์ž๋™ ์ˆ˜ํ–‰ํ•˜๊ฒŒ ํ•˜๋Š” ๊ธฐ๋Šฅ์ด๋‹ค.

ํŠธ๋ฆฌ๊ฑฐ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋ฐ์ดํ„ฐ์˜ ์ž…๋ ฅ, ์ˆ˜์ •, ์‚ญ์ œ ์‹œ ๋กœ๊ทธ๋ฅผ ๊ธฐ๋กํ•˜์—ฌ ํ…Œ์ด๋ธ”์˜ ๋ณ€๊ฒฝ๋‚ด์—ญ์„ ์ถ”์ ํ•  ์ˆ˜ ์žˆ๋‹ค.

TRIGGER์‚ฌ์šฉ ์‹œ ์ง€์ •ํ•ด์•ผํ•  ๊ฒƒ

  • TRIGGER๋Š” ํ…Œ์ด๋ธ”์„ ๋Œ€์ƒ์œผ๋กœ ์‹คํ–‰๋˜๊ธฐ ๋•Œ๋ฌธ์— ๋Œ€์ƒ ํ…Œ์ด๋ธ”์„ ์ง€์ •ํ•œ๋‹ค.

  • INSERT, DELETE, UPDATE ์ค‘ ์–ด๋–ค ์ž‘์—…์ด ๋ฐœ์ƒํ•  ๋•Œ ํŠธ๋ฆฌ๊ฑฐ๋ฅผ ์ˆ˜ํ–‰ํ•˜๋Š”์ง€ ๊ฒฐ์ •ํ•œ๋‹ค.

  • ํŠธ๋ฆฌ๊ฑฐ๋ฅผ ์ž‘์—… ์ „์— ์ˆ˜ํ–‰ํ•ด์•ผํ•˜๋Š”์ง€, ์ž‘์—… ์ดํ›„์— ์ˆ˜ํ–‰ํ•ด์•ผํ•˜๋Š”์ง€ ์ˆ˜ํ–‰ ์‹œ์ ์„ ๊ฒฐ์ •ํ•œ๋‹ค.


ํŠธ๋ฆฌ๊ฑฐ๊ฐ€ ์ƒ์„ฑํ•˜๋Š” ์ž„์‹œ ํ…Œ์ด๋ธ”

ํŠธ๋ฆฌ๊ฑฐ์—๋Š” INSERT, DELETE, UPDATE ์ž‘์—…์ด ์ˆ˜ํ–‰๋˜๋ฉด ์ž„์‹œ๋กœ ์‚ฌ์šฉ๋˜๋Š” ์‹œ์Šคํ…œ ํ…Œ์ด๋ธ”์ด ์žˆ๋‹ค.

  • NEW : INSERT, UPDATE ์ž‘์—…์ด ์ˆ˜ํ–‰๋˜๋ฉด ํ…Œ์ด๋ธ”์— ๋“ค์–ด์˜ฌ ์ƒˆ๋กœ์šด ๋ฐ์ดํ„ฐ๋ฅผ ์ž ๊น ์ €์žฅํ•œ๋‹ค. ๊ทธ ๋’ค, ํ…Œ์ด๋ธ”์—์„œ ์ž…๋ ฅ๊ณผ ๋ณ€๊ฒฝ์ด ๋ฐœ์ƒํ•œ๋‹ค.

  • OLD : DELETE, UPDATE ์ž‘์—…์ด ์ˆ˜ํ–‰๋˜๋ฉด ํ…Œ์ด๋ธ”์˜ ์˜ˆ์ „ ๊ฐ’์ด ์ž ๊น ์ €์žฅ๋œ๋‹ค. ๊ทธ ๋’ค, ํ…Œ์ด๋ธ”์—์„œ ์ž…๋ ฅ๊ณผ ๋ณ€๊ฒฝ์ด ๋ฐœ์ƒํ•œ๋‹ค.



โš  ์ฃผ์˜
๋‹ค๋ฅธ DBMS์—์„œ๋Š” ๋ทฐ์— ๋Œ€ํ•œ ํŠธ๋ฆฌ๊ฑฐ๋ฅผ ์ง€์›ํ•˜๊ธฐ๋„ ํ•˜์ง€๋งŒ
MySQL์—์„œ๋Š” ๋ทฐ์— ๋Œ€ํ•œ ํŠธ๋ฆฌ๊ฑฐ๋ฅผ ์ง€์›ํ•˜์ง€ ์•Š๋Š”๋‹ค.



๐Ÿ’ฟ Trigger ๋ฌธ๋ฒ•

CREATE TRIGGER ํŠธ๋ฆฌ๊ฑฐ์ด๋ฆ„
{BEFORE | AFTER} {INSERT | UPDATE | DELETE} ON ํ…Œ์ด๋ธ”์ด๋ฆ„ 
FOR EACH ROW  -- ๋‹ค์ˆ˜์˜ ๋ ˆ์ฝ”๋“œ๊ฐ€ ๋™์‹œ์— ๋ณ€๊ฒฝ๋˜๋Š” ๊ฒฝ์šฐ ๋ ˆ์ฝ”๋“œ๋ณ„ ํŠธ๋ฆฌ๊ฑฐ ํ˜ธ์ถœ
ํŠธ๋ฆฌ๊ฑฐ ๋กœ์ง;

์˜ˆ์‹œ

-- ๋ณ€๊ฒฝ์‚ฌํ•ญ ๋กœ๊ทธ๋ฅผ ์ €์žฅํ•˜๊ธฐ ์œ„ํ•œ ํ…Œ์ด๋ธ” suranNameGenderAudit ์ƒ์„ฑ.
DROP TABLE IF EXISTS test.suranNameGenderAudit;
CREATE TABLE test.suranNameGenderAudit (
	name varchar(16),
    gender enum('Male', 'Female'),
    modified timestamp
);

-- ํ…Œ์ด๋ธ”์˜ ๋‚ด์šฉ์ด UPDATE ๋˜๊ธฐ ์ง์ „์— ์‹คํ–‰๋˜๋Š” ํŠธ๋ฆฌ๊ฑฐ eforeUpdateSuranNameGender ์ƒ์„ฑ. 
DROP TRIGGER IF EXISTS test.beforeUpdateSuranNameGender;
CREATE TRIGGER test.beforeUpdateSuranNameGender
	BEFORE UPDATE ON test.suRan_name_gender
    FOR EACH ROW 
INSERT INTO test.suranNameGenderAudit
SET name =  OLD.name, -- ๋ฐ”๋€Œ๊ธฐ ์ „ ์ด๋ฆ„
	gender = OLD.gender,
	modified = NOW();
    
    
-- test.suRan_name_genderํ…Œ์ด๋ธ”์˜ ๋‚ด์šฉ ๋ณ€๊ฒฝ    
UPDATE test.suRan_name_gender
SET name = 'Benjamin'
WHERE name = 'Ben';
    




์ •๋ฆฌ

ํŠธ๋ฆฌ๊ฑฐ๋Š” ํ…Œ์ด๋ธ”๊ณผ ๊ด€๋ จ๋œ ์ด๋ฒคํŠธ(INSERT, DELETE, UPDATE)์— ๋ฐ˜์‘ํ•ด ์ž๋™ ์‹คํ–‰๋˜๋Š” ์ž‘์—…์ด๋‹ค.

Ref
https://title-developer.tistory.com/146

profile
๊ฐœ๋ฐœ ๊ณต๋ถ€๋ฅผ ํ•ด๋ผ

2๊ฐœ์˜ ๋Œ“๊ธ€

comment-user-thumbnail
2022๋…„ 7์›” 17์ผ

์ž˜ ์ฝ์—ˆ์Šต๋‹ˆ๋‹ค.

1๊ฐœ์˜ ๋‹ต๊ธ€