📅  最后修改于: 2023-12-03 15:33:18.810000             🧑  作者: Mango
Oracle DECODE is a very powerful and useful function in SQL. It is used to compare an expression against one or more conditions and return a result when a match is found. The syntax of the DECODE function is as follows:
DECODE (expression, search1, result1, search2, result2,..., default)
In this example, we will use DECODE to convert a score into a grade. The score can range from 0 to 100 and we want to assign grades from A to F. Here's how we can do it:
SELECT DECODE (score,
90, 'A',
80, 'B',
70, 'C',
60, 'D',
'F') AS grade
FROM grades;
In this example, we are comparing the score with the search conditions (90, 80, 70, and 60) and returning the appropriate grade based on the match. If the score does not match any of the search conditions, we return 'F'.
In this example, we will use DECODE to create a new column 'is_manager' in the employees table based on whether an employee is a manager or not. Here's how we can do it:
SELECT employee_id, first_name, last_name,
DECODE (job_id, 'AD_PRES', 'Y', 'AD_VP', 'Y', 'SA_MAN', 'Y', 'N') AS is_manager
FROM employees;
In this example, we are comparing the job_id with the search conditions ('AD_PRES', 'AD_VP', and 'SA_MAN') and returning 'Y' if there is a match. If there is no match, we return 'N'. We are also creating a new column 'is_manager' in the result set.
DECODE is a very versatile function in Oracle SQL. It allows us to perform conditional checks in a concise and efficient way. By mastering this function, you can simplify your SQL code and make it more readable and maintainable.