oracle入门10

来源:互联网 发布:11选5旋转矩阵公式演示 编辑:程序博客网 时间:2024/05/21 08:50

 

PL/SQL编程

 PL/SQLoracle的专用语言,它对标准的SQL语言的扩展.SQL语句可以嵌套在PL/SQL语言中,并结合处理语句。

 

PL/SQL程序结构

  使用了程序块的结构组织的代码.最简单的程序块是一种被称为匿名块的程序块,匿名块是指不会被oracle存储并且不能够重用程序块。

PL/SQL程序通常包括3部分:Declare部分、exception部分、Beginend部分.

BeginendPL/SQL的必须部分,总是begin开始end结束.

 

Declare部分包含定义变量、常量和游标等类型的代码.

 

Beginend之间可以嵌套beginendexception.

 

//打开服务器的输出

SQL> set serveroutput on;

SQL> begin //开始

  2 dbms_output.put_line('Hello World');

  3  end;

  4  /

 

 

//声明一个整型的变量

SQL> declare

  2   agenumber(2);

  3 begin

  4 age:=90;

  5 dbms_output.put_line(age);

  6  end;

  7  /

//声明后直接赋值

SQL> declare

  2   agenumber(2) :=90;

  3 begin

  4 dbms_output.put_line(age);

  5  end;

  6  /

//捕获异常处理

SQL> declare

  2  agenumber(2);

  3 begin

  4  age:='qwe'

  5  ;

  6 exception

  7  whenothers then

  8 dbms_output.put_line('赋值失败');

  9  end;

 10  /

 

 

条件判断语句

  ifcase语句

  

  If语句

If语法

   Ifexpression1thenpl/sql_statement

   Else

        Pl/sql_statement;

   End if;

  

Ifexpression1thenpl/sql_statement

   Else ifexpression2

        Pl/sql_statement;

   Else

        Pl/sql_statement;

   End if;

  

 

 Case语句

     oracle9i以后引入

     Case<selector>

       When <expression1> then pl/sql_statement1;

       When <expression2> then pl/sql_statement2;

       …….

       [else  pl/sql_statement;]

     End;

//案例

SQL> declare score number(2):=80;

   begin

       if score>70 thendbms_output.put_line('成绩合格');

   end if;

   end;

  /

 

SQL> declare score number(2):=80;

   begin if score>90 thendbms_output.put_line('成绩合格');

 else dbms_output.put_line('成绩不合格');

end if;

end;

/

 

成绩不合格

 

 

SQL> declare scorenumber(2):=8;

begin

case score

when 9 thendbms_output.put_line('成绩优秀');

when 8 thendbms_output.put_line('成绩亮');

end case;

end;

 /

 

循环语句

  最基本的循环称为无条件循环,如果没有指定exit语句,循环将无条件执行,这种循环称为死循环,死循环尽量避免。

语法格式如下:

     Loop

       ---statement---

 Exitwhen condition

 Endloop;

 

案例:

SQL> declare

      i number(2):=1;

       begin

            loop

              dbms_output.put_line(i);

                   i:=i+1;

          exit when i>10;

          end loop;

          end;

   /

 

While循环

    语法:

    Whilecondition

        Loop

          Statement;

       End loop;

 

SQL> declare

     i number(2):=1;

         begin

           while i<10   

              loop dbms_output.put_line(i);

                i:=i+1;

             end loop;

          end;

  /

 

For循环

     Forloop_control_variable in [reverse] lower upper loop

         Statement;

       End loop;

 

 SQL> begin

         for i in 1..10

            loop

            dbms_output.put_line(i);

           end loop;

       end;

      /

 

 

集合操作

存储过程

触发器

原创粉丝点击