PL/SQL developer基礎語法學習(二)之語法

一、sql的dml

1)、查詢,運用 select into

實例(只能查詢的單個數據:有且只有一個值  “不能有多個值,不能爲空”):
/**
操作 select  ,使用 select  into
*/
declare 
   v_ename emp.ename%type;
begin 
   --獲取 工資爲 800的員工姓名
   select ename into v_ename from emp where sal=800;   
   dbms_output.put_line(v_ename);
end;

除此之外,還可以添加異常處理
例如:
--加入異常
declare 
   v_ename emp.ename%type;
begin 
   --獲取 工資爲 800的員工姓名
   select ename into v_ename from emp where sal=&月薪;   
   dbms_output.put_line(v_ename);
exception 
   when  no_data_found then
        dbms_output.put_line('數據未找到'||sqlcode||'-->'||sqlerrm);  
   when too_many_rows then
        dbms_output.put_line('數據超出'||sqlcode||'-->'||sqlerrm);  
   when others then
        dbms_output.put_line('其他異常'||sqlcode||'-->'||sqlerrm);  
end;

二、異常

異常 exception: 非正常情況

1、no_data_found :數據未找到

2、to_many_rows :數據太多

3、others


三、控制語句

1.選擇語句

1)格式如下
if  then 
elsif  then
…
else
end if;
2)實例:
--計算年薪
declare
    --獲取員工的 獎金
    v_income emp.sal%type;
begin
    execute immediate 'select (nvl(comm,0)+sal)*12 from emp where empno=&員工編號 ' into v_income;
    --判斷
    if v_income<10000 then
       dbms_output.put_line('1');
    elsif v_income<50000  then
      dbms_output.put_line('2');   
    else
      dbms_output.put_line('不錯');     
    end if;
  
exception 
   when  no_data_found then
        dbms_output.put_line('數據未找到'||sqlcode||'-->'||sqlerrm);  
   when too_many_rows then
        dbms_output.put_line('數據超出'||sqlcode||'-->'||sqlerrm);  
   when others then
        dbms_output.put_line('其他異常'||sqlcode||'-->'||sqlerrm);  
end;

2、循環

循環四要素:  初始表達式 條件表達式  迭代因子 循環體

1)、直到型(先執行後判斷)

格式爲:
loop 
    exit when 條件
end loop;

實例:
--直到型
declare
   --100以內的奇數
   --1、初始化表達式
   v_num number(5):=1; 
begin 
  loop      
     --2、循壞體
     if mod(v_num,2)=1  then  
        dbms_output.put_line(v_num);
     end if;
    exit when v_num>=100;  --3、條件    
    --4、迭代因子
    v_num :=v_num+1;
  end loop;
end;


2)、當到型

格式爲:
while 條件  loop

end loop;

實例:
--當到型
declare
   --100以內的奇數
   --1、初始化表達式
   v_num number(5):=1; 
begin 
   --3、條件
  while v_num<=100 loop      
     --2、循壞體
     if mod(v_num,2)=1  then  
        dbms_output.put_line(v_num);     
     end if;  
    --4、迭代因子
    v_num :=v_num+1;
  end loop;
end;


3)、for

變量不需要聲明 變量,變量的值不能改變,內部值+1

格式:

for index in [reverse] min..max loop

end loop  


實例

declare
   --1..100的奇數
   --初始化表達式
   v_num number(5):=1; 
begin 
 for i in 1..100  loop   
   if mod(i,2)=1 then  
      dbms_output.put_line(i);   
   end if; 
 end loop;
end;

for的內部倒敘操作 reverse

實例

--for  (倒轉輸出)
declare
   --1..100的數
   --1、初始化表達式
   v_num number(5):=1; 
begin 
 for i in reverse 1..100  loop
   dbms_output.put_line(i);     
 end loop;
end;















發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章