Equivalent DB2 syntax for the Oracle DECODE function
Is there an equivalent DB2 syntax for the Oracle DECODE function?
Continue Reading This Article
Enjoy this article as well as all of our content, including E-Guides, news, tips and more.
Well, first of all, let's explain the Oracle DECODE expression for those not familiar with Oracle. A DECODE expression will look like this:
DECODE(expr,search,result,default)
There can be multiple search values and results, and default is optional. To evaluate this expression, Oracle compares expr to each search value one by one. If expr is equal to a search, Oracle returns the corresponding result. If no match is found, Oracle returns default, or, if default is omitted, null is returned. If expr and search contain character data, Oracle compares them using nonpadded comparison semantics. The maximum number of components in the DECODE expression, including expr, searches, results, and default is 255.
So, basically, DECODE changes the value of an expression if the expression is equal to one of the values in the searched list. For example, this expression decodes the value deptno. If deptno is 10, the expression evaluates to 'ACCOUNTING'; if deptno is 20, it evaluates to 'RESEARCH'; etc. If deptno is not 10, 20, 30, or 40, the expression returns 'NONE'.
DECODE (deptno,10, 'ACCOUNTING', 20, 'RESEARCH', 30, 'SALES', 40, 'OPERATION', 'NONE')
In DB2 this can be accomplished using CASE expression. To write the equivalent of the above using DB2 you can write the following SQL statement:
SELECT CASE deptno WHEN 10 THEN 'ACCOUNTING' WHEN 20 THEN 'RESEARCH' WHEN 30 THEN 'SALES' WHEN 40 THEN 'OPERATIONS' ELSE 'NONE' END CASE FROM EMP;
For More Information
- Dozens more answers to tough DB2 questions from Craig Mullins are available.
- The Best IBM DB2 Web Links: tips, tutorials, scripts, and more.
- Have a DB2 tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize. Submit your tip today!
- Ask your technical DB2 questions -- or help out your peers by answering them -- in our live discussion forums.
- Ask the Experts yourself: Our SQL, database design, Oracle, SQL Server, DB2, metadata, object-oriented and data warehousing gurus are waiting to answer your toughest questions.