TIL - 프로그래밍/SQL

[SQL] 사용자 정의 함수

chaemj97 2023. 7. 8. 01:40
728x90

기본 구조

CREATE FUNCTION 함수 이름 (파라미터 이름 데이터 타입,)
	RETURNS 출력될 결과의 데이터 타입 (DETERMINISTIC)
BEGIN
	DECLARE 변수 이름, 데이터 타입;
    SET ;
    RETURN (쿼리) / 데이터 이름;
END

# 사용 방법
SELECT 함수 이름 (파라미터)
  • DETERMINISTIC 을 쓰면 INPUT 값이 같을 때 항상 똑같은 OUTPUT 값이 나옴

 

예시

https://www.mysqltutorial.org/mysql-stored-function/

 

MySQL Stored Function By Practical Examples

In this tutorial, you will learn how to create MySQL stored functions by using the CREATE FUNCTION statement.

www.mysqltutorial.org

  • 문제
    • customers 테이블에서 customerLevel 구하기
      • customerLevel은 creditLimit에 의해 정해진다.
        • 50,000 초과 PLATINUM
        • 10,000 이상 GOLD
        • 나머지 SILVER
  • SQL 코드
-- 함수 선언
CREATE FUNCTION CustomerLevel (creditLimit DECIMAL(10,2))
    RETURNS VARCHAR(20) DETERMINISTIC
BEGIN
    DECLARE Level VARCHAR(20);
    IF creditLimit > 50000 THEN
    	SET Level = 'PLATINUM';
    ELSEIF creditLimit >= 10000 THEN
    	SET Level = 'GOLD';
    ELSE
    	SET Level = 'SILVER';
    END IF;
    RETURN Level;
END

-- 함수 사용
SELECT customerName, CustomerLevel(creditLimit)
FROM customers
ORDER BY customerName;

 

관련 문제 풀이

https://chaemi720.tistory.com/342

 

[리트코드] 177. Nth Highest Salary - MySQL

https://leetcode.com/problems/nth-highest-salary/ Nth Highest Salary - LeetCode Can you solve this real interview question? Nth Highest Salary - Table: Employee +-------------+------+ | Column Name | Type | +-------------+------+ | id | int | | salary | in

chaemi720.tistory.com

 

728x90
반응형