在现实生活中,当我们需要做一些决定时,我们会根据这些决定来决定下一步该做什么。在编程中也会出现类似的情况,我们需要做出一些决定,并根据这些决定执行下一段代码。
null
编程语言中的决策语句决定程序执行的方向。pl/SQL中可用的决策语句包括:
- if-then语句
- if-then-else语句
- 嵌套的if-then语句
- 如果那么elsif那么else梯子
- if-then语句 if-then语句是最简单的决策语句。它用于决定是否执行某个语句或语句块,即如果某个条件为真,则执行语句块,否则不执行。
语法:
if condition then -- do something end if;
在这里,评估后的条件将为真或假。如果语句接受布尔值——如果该值为真,则它将执行下面的语句块,否则不会执行。 如果和Endif考虑作为一个块在这里。
例如:-
SQL
declare
-- declare the values here
begin
if condition
then
dbms_output.put_line(
'output'
);
end
if;
dbms_output.put_line(
'output2'
);
end
;
SQL
-- pl/sql program to illustrate If statement
declare
num1 number:= 10;
num2 number:= 20;
begin
if num1 > num2
then
dbms_output.put_line(
'num1 small'
);
end
if;
dbms_output.put_line(
'I am Not in if'
);
end
;
因为if语句中存在的条件是错误的。因此,if语句下面的块不会被执行。 输出:
I am Not in if
- 如果——那么——否则: if语句本身告诉我们,如果一个条件为真,它将执行一组语句,如果条件为假,它将不会执行。但是如果条件为假,我们想做些别的事情呢。下面是else的声明。当条件为false时,我们可以使用else语句和if语句来执行代码块。 语法:-
if (condition) then -- Executes this block if -- condition is true else -- Executes this block if -- condition is false
例如:-
SQL
-- pl/sql program to illustrate If else statement
declare
num1 number:= 10;
num2 number:= 20;
begin
if num1 < num2
then
dbms_output.put_line(
'i am in if block'
);
ELSE
dbms_output.put_line(
'i am in else Block'
);
end
if;
dbms_output.put_line(
'i am not in if or else Block'
);
end
;
输出:-
i'm in if Block i'm not in if and not in else Block
else语句后面的代码块在调用不在块中的语句(不带空格)后执行,因为if语句中的条件为false。
- 嵌套,如果: 嵌套if-then是另一个if语句的目标if语句。嵌套的if-then语句表示另一个if语句中的if语句。是的,PL/SQL允许我们在if then语句中嵌套if语句。i、 我们可以把一个if-then语句放在另一个if-then语句中。
语法:-
if (condition1) then -- Executes when condition1 is true if (condition2) then -- Executes when condition2 is true end if; end if;
SQL
-- pl/sql program to illustrate nested If statement
declare
num1 number:= 10;
num2 number:= 20;
num3 number:= 20;
begin
if num1 < num2
then
dbms_output.put_line(
'num1 small num2'
);
if num1 < num3
then
dbms_output.put_line(
'num1 small num3 also'
);
end
if;
end
if;
dbms_output.put_line(
'after end if'
);
end
;
输出:-
num1 small num2 num1 small num3 also after end if
- 如果那么elsif那么else梯子 在这里,用户可以在多个选项中进行选择。if-then语句自上而下执行。一旦控制if的条件之一为真,就会执行与该if关联的语句,并绕过梯形图的其余部分。如果所有条件都不成立,那么将执行最终的else语句。
语法:-
if (condition) then --statement elsif (condition) then --statement . . else --statement endif
流程图:-
例如:-
SQL
-- pl/sql program to illustrate if-then-elif-then-else ladder
declare
num1 number:= 10;
num2 number:= 20;
begin
if num1 < num2
then
dbms_output.put_line(
'num1 small'
);
ELSIF num1 = num2
then
dbms_output.put_line(
'both equal'
);
ELSE
dbms_output.put_line(
'num2 greater'
);
end
if;
dbms_output.put_line(
'after end if'
);
end
;
输出:-
num1 small after end if
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END