sql stored procedure返回結果集的操作步驟:
1)declare cursor:
如:
- declare clIEntcur cursor with return to caller for select * from staff;
2)open the cursor:如 open clIEntcur;
3)不關閉游標退出stored procedure
開發:
最後終於來到了真正的開發了,剛才講到sql procedure是由sql,sql pl寫的,sql就沒什麼好說的了。關鍵說說sql pl (procedural language)
功能:控制邏輯流向,聲明和設置變量,處理警告和異常。可用於例程(routine),觸發器,動態復合語句(單個調用中的sql語句塊)
控制語句:declare,set,for,get diagnostics,if,iterate,leave,return,signal,while
sql pl不能執行的sql:table,index,vIEw的create和drop
begin atomic 開頭,end 結尾
declare :定義變量 和 定義出錯處理
- declare sql-var-name data-type default default-values
- declare condition-name condition for sqlstate value...
這裡的condition一般做“異常”解釋
set:聲明變量 和 給觸發器定義中的表中的列賦值
set pay = select salary from employee where empno = 5;//僅返回一個值
set pay = null;//空值
set pay = default;//變量定義的默認值
//專用寄存器的內容
- set useriduserid = userid;
- set today = current date;
//同時給多個變量賦值
- set pay =10000,bonus = 1500;
- set (pay,bonus) = (10000,1500);
- set (pay,bonus) = select (pay,bonus) from employee where empno = 5;
- >>if/then/else
三種形式:
1) if then/end if 語句塊
2) if then/else/end if
3) if then/elseif /else/end if
可以在if/then/else 語句中使用sql運算符,如:
- if (salary between 10000 and 90000) then...
- if (deptno in ('a00','b01')) then..
- if (exist (select * from employee)) then...
- if (select count(*) from employee)>0) then..
- >>while
- label:
- while condition do
- ...sql pl ..
- end while lable;
label可選
>>for:用於循環select返回結果集的行
格式:
- label:
- for row_label as select satement do
- ..sql pl..
end for label;//label可選
例子:
- for emp as select * from employee where bonus >1000 do
- set total_bonustotal_bonus = total_bonus +emp.bonus;
- end for;
>>iterate:用來回到for或者while循環的開始重新執行
- check_bonus:
- for emp as select * from employee do
- if(emp.bonus>10000) then
- set total_bonustotal_bonus = total_bonus +emp.bonus;
- else
- iterate check_bonus;
- end if;
- end for check_bonus;
>>leave:相當於Java中的break,需要一個label
>>signal:對出現異常的應用程序報警
signal sqlstate value set message_text = '...';//自定義一個sqlstate,7、8、9和I~Z開頭的sqlstate
signal condition set message_text = '...';//自定義異常condition
>>get diagnostics:用在sql pl觸發器或語句塊(不是函數)內,返回update,insert,delete語句影響的記錄數。
- get diagnostics variable = row_count;
以上的相關內容就是對DB2 sql 存儲過程基礎的詳細解析的介紹,望你能有所收獲。