Oracle之PL/SQL编程_流程控制语句
选择语句 1. if...then 语句 语法: if<condition_expression>then plsql_sentence endif; condition_expression:表示一个条件表达式,其值为 true 时,程序会执行 if 下面的 PL/SQL 语句; 如果其值为 false,则程序会跳过if 下面的语句而 直接执行 end if 后边的语句。 plsql_sentence:condition_expression 为 true 时,要执行的语句。 2. if...then...else 语句 语法: if<condition_expression>then plsql_sentence_1; else plsql_sentence_2; endif; 3.if...then...elsif 语句 语法: if<condition_expression1>then plsql_sentence_1; elsif<condition_expression2>then plsql_sentence_2; ... else plsql_sentence_n; endif; 4. case 语句 语法: case<selector> when<expression_1>thenplsql_sentence_1; when<expression_2>thenplsql_sentence_2; ... when<expression_n>thenplsql_sentence_n; [elseplsql_sentence;] endcase; selector:一个变量,用来存储要检测的值,通常称之为选择器。 该选择器的值需要与 when 子句中的表达式的值进行匹配。 expression_1:第一个 when 子句中的表达式,这种表达式通常是一个常量,当选择器的值等于该表达式的值时, 程序将执行 plsql_setence_1 语句。 expression_2:第二个 when 子句中的表达式,这种表达式通常是一个常量,当选择器的值等于该表达式的值时, 程序将执行 plsql_setence_2 语句。 expression_n:第 n 个 when 子句中的表达式,这种表达式通常是一个常量,当选择器的值等于该表达式的值时, 程序将执行 plsql_setence_n 语句。 plsql_sentence:一个 PL/SQL 语句,当没有与选择器匹配的 when 常量时,程序将执行该 PL/SQL 语句, 其所在的 else 语句是一个可选项。 例: 指定一个季度数值,然后使用 case 语句判断它所包含的月份信息并输出。 代码: declare seasonint:=3; aboutlnfovarchar2(50); begin caseseason when1then aboutlnfo:=season||'季度包括1,2,3月份'; when2then aboutinfo:=season||'季度包括4,5,6月份'; when3then aboutinfo:=season||'季度包括7,8,9月份'; when4then aboutinfo:=season||'季度包括10,11,12月份'; else aboutinfo:=season||'季节不合法'; endcase; dbms_output.put_line(aboutinfo); end; 结果:3季度包括7,9 月份 循环语句 1. loop 语句 语法: loop plsql_sentence; exitwhenend_condition_exp endloop; plsql_sentence:循环体中的PL/SQL 语句。至少被执行一遍。 end_condition_exp:循环结束条件表达式,当该表达式为 true 时,则程序会退出循环体,否则程序将再次执行。 例: 使用 loop 语句求得前 100 个自然数的和,并输出到屏幕。 SQL>setserveroutputon; SQL>declare sun_iint:=0; iint:=0; begin loop i:=i+1; sum_i:=sum_i+1; exitwheni=100;--当循环100次,程序退出循环体。 endloop; dbms_output.put_line('前100个自然数和:'||sum_i); end; / 2. while 语句 语法: whilecondition_expressionloop plsql_sentence; endloop; condition_expression: 表示一个条件表达式,但其值为 true 时,程序执行循环体。 否则 程序退出循环体,程序每次执行循环体之前,都判断该表达式是否为 true。 plsql_sentence:循环内的plsql语句。 例: 使用while 语句求得 前100 个自然数的和,并输出到屏幕。 declare sum_iint:=0; iint:=0; begin whilei<=99loop i:=i+1; sum_i:=sum_i+1; endloop; dbms_output.put_line('前100个自然数的和是:'||sum_i); end; / 3. for 语句 语法: forvariable_counter_namein[reverse]lower_limit..upper_limitloop plsql_sentence; endloop; variable_counter_name:表示一个变量,通常为整数类型,用来作为计数器。 默认情况下 计数器的值会递增,当在循环中使用 reverse 关键字时,计数器的值会随循环递减。 lower_limit:计数器下限值,当计数器的值小于下限值时,退出循环。 upper_limit:计数器上限值,当计数器的值大于上限值时,退出循环。 plsql_sentence:循环内的plsql语句。 例: 使用for语句求得前 100个自然数中偶数之和,并输出到屏幕。 declare sum_iint:=0; begin foriinreverse1..100loop ifmod(i,2)=0then--判断是否为偶数 sum_i:=sum_i+i; endif; endloop; dbms_output.put_line('前100个自然数中偶数和:'||sum_i); end; / (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |