1. 程式人生 > >【oracle 流程控制】oracle資料庫流程控制語句控制PL/SQL語句

【oracle 流程控制】oracle資料庫流程控制語句控制PL/SQL語句

1、條件語句 if else判斷

#宣告變數
declare employee_sa  number;
begin
select count(*) into employee_sa from employees where salary>6000;
if employee_sa=1 then 
dbms_output.put_line('本公司有一名薪資大於6000的員工');
elsif  employee_sa>1 then 
dbms_output.put_line('本公司有多名薪資大於6000的員工');
esle
dbms_output.put_line('本公司沒有薪資大於6000的員工');
end if;
end;

2、case when 分支判斷

#宣告變數
declare employee_sa  number;
begin
select count(*) into employee_sa from employees where salary>6000;
case when employee_sa=0 then 
dbms_output.put_line('本公司沒有薪資大於6000的員工');
when employee_sa=1 then 
dbms_output.put_line('本公司有一名薪資大於6000的員工');
else 
dbms_output.put_line('本公司有多名薪資大於6000的員工');
end case;
end;

3、無條件迴圈

#無條件迴圈
-- loop
 -- 迴圈操作
 -- end loop
#利用無條件迴圈輸出員工employee_id 處於100~106 之間的所有員工姓名
declare e_id number:=100;
declare e_name varchar2(20);
begin
	loop
		if e_id>=106 then
		exit;
		end if;

		e_id:=e_id+1;
		select first_name into e_name from employees where employee_id=e_id;
		dbms_output.put_line(e_id|| '號員工是:'|| e_name);
	end loop;

end;

4、while 迴圈

#語法
-- while 條件判斷 loop
-- 迴圈操作
-- end loop;

declare e_id number:=100;
declare e_name varchar2(20);
begin
	while e_id<106 loop
	
		e_id:=e_id+1;
		select first_name into e_name from employees where employee_id=e_id;
		dbms_output.put_line(e_id|| '號員工是:'|| e_name);
	end loop;

end;

5、for 迴圈

#語法(注意:or 迴圈自行宣告變數,因此無需對e_id 宣告)
-- for counter
-- in lower_bound upper_bound
-- loop
-- 迴圈操作
-- end loop;

declare e_name varchar2(20);
begin
	for e_id in 100..106 loop
		select first_name into e_name from employees where employee_id=e_id;
		dbms_output.put_line(e_id|| '號員工是:'|| e_name);
	end loop;
end;