-
mariaDB) 사용자 정의 함수(User-Defined Function) 만들기SQL/sql 문법(mysql, mariaDB) 2024. 5. 21. 20:24
▤ 목차
✔ 사용자 정의 함수 만들기
DBMS에서 제공하는 내장함수가 아니고 사용자가 직접 정의하는 함수를 말한다.
절차형 SQL을 활용하여 일련의 SQL 처리를 수행하고 수행 결과를 단일 값으로 반환한다.
단일 값을 제공하는 특별한 형태로 저장된 일종의 프로그램으로 공통적으로 적용할 기능이나 비즈니스를 캡슐화 하기 위해서 Function을 사용할 수 있다.
⌨ 형식
delimiter // CREATE OR REPLACE FUNCTION fu() RETURNS DOUBLE BEGIN END; // delimiter ;
기본적인 개념 및 사용법, 문법 등으 프로시저와 동일하다.
다만 반환값이 존재하는 것이 큰 차이점이 있다.
💻 코드로 보기
# BMI 계산 함수 만들기
> 표준체중(bmi값 22기준) = 신장(CM) * 신장(CM) * 22 / 10000
delimiter $$ CREATE OR REPLACE FUNCTION fu1(height INT) RETURNS DOUBLE BEGIN RETURN height * height *22 / 10000; END; $$ delimiter ;
SELECT fu1(175);
# 각 직원의 부서명 반환하기
delimiter // CREATE OR REPLACE FUNCTION fu4(NO int) RETURNS VARCHAR(10) CHARSET UTF8 BEGIN DECLARE bname VARCHAR(10) CHARSET UTF8; SELECT buser_name INTO bname FROM buser WHERE buser_no = (SELECT buser_num FROM jikwon WHERE jikwon_no=no); RETURN bname; END; // delimiter ; SELECT fu4(3);
😊참고 사이트
https://docs.snowflake.com/ko/developer-guide/udf/udf-overview
https://benggri.tistory.com/77
'SQL > sql 문법(mysql, mariaDB)' 카테고리의 다른 글
MariaDB) 사용자 계정 생성 및 권한 부여 (0) 2024.05.22 저장 프로시저 (Stroed Procedure) (0) 2024.05.20 MariaDB) 간단한 DB 백업과 복원 (mysqldump 사용) (0) 2024.05.17 트랜잭션(transection): deadlock (2) 2024.05.16 트렌젝션(transections)과 ACID (0) 2024.05.15