(1)存储过程结构:
AS/IS在存储过程(PROCEDURE)和函数(FUNCTION)中没有区别;在视图(VIEW)中只能用AS不能用IS;在游标(CURSOR)中只能用IS不能用AS。
CREATE OR REPLACE PROCEDURE 存储过程名字 ( 参数1 IN NUMBER, 参数2 IN NUMBER ) IS 变量1 INTEGER :=0; 变量2 DATE; BEGIN --执行体 END 存储过程名字;
(2)变量赋值:
V_TEST := 123;
(3)SELECT INTO STATEMENT
--将select查询的结果存入到变量中,可以同时将多个列存储多个变量中,必须有一条记录,否则抛出异常(如果没有记录抛出NO_DATA_FOUND)
BEGIN --执行体 SELECT col1,col2 into 变量1,变量2 FROM typestruct where xxx; EXCEPTION WHEN NO_DATA_FOUND THEN -- select into 语句没有符合条件的记录返回 xxxx; END;
(4)IF 语句:
IF V_TEST = 1 THEN BEGIN do something END; END IF;
(5)WHILE 语句
WHILE V_TEST=1 LOOP BEGIN XXXX END; END LOOP;
(6)FOR 语句
FOR CUR_PARAM IN CUR_PARAMS LOOP BEGIN XXXX END; END LOOP;
(7)CURSOR 使用
1)FOR IN 方式:
IS CURSOR cur IS SELECT * FROM xxx; BEGIN FOR cur_result in cur LOOP BEGIN V_SUM :=cur_result.列名1+cur_result.列名2 END; END LOOP; END;
2)非FOR IN方式无参:
CURSOR C_USER IS SELECT NAME FROM USER; OPEN C_USER; FETCH C_USER INTO V_NAME; EXIT WHEN FETCH C_USER%NOTFOUND; CLOSE C_USER;
3)非FOR IN方式带参CURSOR:
CURSOR C_USER(C_ID NUMBER) IS SELECT NAME FROM USER WHERE TYPEID=C_ID; OPEN C_USER(变量值); FETCH C_USER INTO V_NAME; EXIT WHEN FETCH C_USER%NOTFOUND; CLOSE C_USER;
(1)方式一:直接定义游标
create or replace procedure test1 is begin declare cursor emp_sor is select ename,sal from emp where deptno=10; cname emp.ename%type; csal emp.sal%type; begin open emp_sor; loop fetch emp_sor into cname,csal; --取游标的值给变量。 exit when emp_sor%notfound; dbms_output.put_line('ename:'||cname||'sal'||csal); end loop; close emp_sor; end; end test1;
(2)方式二:用for取值,带隐式游标会自动打开和关闭
create or replace procedure test2 is begin declare cursor emp_sor is select a.ename from emp a; type emp_table_type is table of varchar(20); begin for emp_record in emp_sor loop dbms_output.put_line('第'||emp_sor%rowcount||'雇员名:'||emp_record.ename); end loop; end; end test2;