Oracle其他函数

来源:互联网 发布:日本刀 知乎 编辑:程序博客网 时间:2024/05/21 13:56

其他函数

NVL

语法如下:
      NVL( string, replace_with)
功能描述:
      如果string为NULL,则NVL函数返回replace_with的值,否则返回string的值。

NVL2

语法如下:
      NVL2(expr1,expr2, expr3)
功能描述:
      如果该函数的第一个参数为空那么显示第三个参数的值,如果第一个参数的值不为空,则显示第二个参数的值。

SIGN

      sign函数返回一个数字的正负标志。
      sign(n):取数字n的符号,大于0返回1,小于0返回-1,等于0返回0。
备注:
      该函数也可以用于比较字段的大小:
      select sign(salary -8000)fromemployee

DECODE

语法如下:
      DECODE的语法:DECODE(value, if1, then1, if2, then2, if3, then3, ..., else)
      表示如果value 等于if1时,DECODE函数的结果返回then1,...,如果不等于任何一个if值,则返回else。初看一下,DECODE只能做等于测试,但我们通过一些函数或计算替代value,是可以使DECODE函数具备大于、小于或等于功能。
      DECODE(条件,值1,翻译值1,值2,翻译值2,...值n,翻译值n,缺省值)
      DECODE(字段,比较1,值1,比较2,值2,.....,比较n,值n缺省值) 
例子:

     1.假设我们想给智星职员加工资,其标准是:工资在8000元以下的将加20%;工资在8000元以上的加15%。

      SQL语句:

    select decode(sign(salary - 8000), 1, salary*1.15 , -1, salary * 1.2,salary from employee

      2. 有学生成绩表student,现在要用decode函数实现以下几个功能:成绩>=85,显示优秀;>=70显示良好;>=60及格;否则是不及格。

      假设student的编号为id,成绩为score,那么:

    select id,decode(sign(score-85),1,'优秀',0,'优秀',-1,           decode(sign(score-70),1,'良好',0,'良好',-1,           decode(sign(score-60),1,'及格',0,'及格',-1,'不及格')))         from student;

CASE

语法如下:
1. 简单CASE表达式,使用表达式确定返回值:
  

CASE search_expression

WHENexpression1THEN result1

WHENexpression2THEN result2

...

WHENexpressionNTHEN resultN

ELSEdefault_result

例子:

select product_id,         product_type_id,        caseproduct_type_id          when1then'Book'          when2then'Video'          when3then'DVD'          when4then'CD'          else'Magazine'        end   from products

2.搜索CASE表达式,使用条件确定返回值:

CASE

WHENcondition1THEN result1

WHENcondition2THEN result2

...

WHENconditionNTHEN resultN

ELSEdefault_result

END

例子:

select product_id,         product_type_id,         case           whenproduct_type_id =1then'Book'           whenproduct_type_id =2then'Video'           whenproduct_type_id =3then'DVD'           whenproduct_type_id =4then'CD'           else'Magazine'         end    from products

原创粉丝点击