PLSQL语句
DECLARE 声明部分
BEGIN 程序编写,SQL语句
EXECPTION 处理异常
END;
/
声明部分(DECLARE)
SQL> set serveroutput on –打开输出
SQL> declare
2 v_num number;
3 begin
4 v_num:=30;
5 dbms_output.put_line(‘V_NUM’||v_num);
6 end;
7 /
V_NUM30
查找empno为7900的员工的名字
declare
v1 scott.emp.ename%type;
v2 scott.emp.sal%type;
begin
select ename,sal into v1,v2 from scott.emp where empno=7900;
dbms_output.put_line(‘ename:’||v1);
dbms_output.put_line(‘sal:’||v2);
end;
/
set serveroutput on
/
查找雇员号和姓名
set serveroutput on
declare
v_eno number;
v_ename varchar2(10);
begin
v_eno:=&empno;
select ename into v_ename from emp where empno=v_eno;
dbms_output.put_line(‘number:’||v_eno||’name:’||v_ename);
end;
/
求平均工资
SQL> !vi test.sql
SQL> !cat test.sql
declare
v_avgsal number(6,2);
begin
select avg(sal) into v_avgsal from scott.emp where deptno=&no;
dbms_output.put_line(‘avg_sal:’||v_avgsal);
end;
SQL> @test.sql
7 /
Enter value for no: 20
old 4: select avg(sal) into v_avgsal from scott.emp where deptno=&no;
new 4: select avg(sal) into v_avgsal from scott.emp where deptno=20;
PL/SQL procedure successfully completed.
声明变量的语法
组成:
CONSTANT:定义常量
NOT NULL:表示此变量不允许设置为NULL
:=value:表示在变量声明时,设置好其初始化内容
DECLARE
V_resultA CONSTANT NUMBER NOT NULL:=100;
BEGIN
DBMS_OUTPUT.put_line(‘v_resultA常量内容:’||(v_resultA));
END;
/
使用%TYPE声明变量类型(对列类型赋值)
DECLARE
eno emp.emono%TYPE;
ename emp.ename%TYPE;
BEGIN
DBMS_OUTPUT.put_line(‘请输入雇员编号:’);
dbms_output.put_line(‘sal:’||v2);
end;
使用%ROWTYPE标记可以定义表中一行记录的类型(对行类型赋值)
SQL> DECLARE
2 deptRow dept%ROWTYPE;
3 BEGIN
4 SELECT * INTO deptRow FROM dept WHERE deptno=10;
5 DBMS_OUTPUT.put_line(‘deptno:’||deptRow.deptno||’,name:’||deptRow.dname||’,loc:’||deptRow.loc);
6 end;
7 /
使用关系运算符
DECLARE
v_url VARCHAR2(50):=’www.vdedu.com.cn’;
v_num1 NUMBER:=80;
v_num2 NUMBER:=30;
BEGIN
IF v_num1>v_num2 THEN
DBMS_OUTPUT.put_line(‘A’);
END IF;
IF v_url LIKE ‘%vdedu%’ THEN
DBMS_OUTPUT.put_line(‘includes vdedu’);
END IF;
END;
AND OR NOT运算符
DECLARE
v_flag1 BOOLEAN:=TRUE;
v_flag2 BOOLEAN:=FALSE;
v_flag3 BOOLEAN;
BEGIN
IF v_flag1 and (NOT v_flag2) THEN
DBMS_OUTPUT.PUT_LINE(‘1’);
END IF;
IF v_flag1 or v_flag3 THEN
DBMS_OUTPUT.PUT_LINE(‘2’);
END IF;
IF v_flag1 and v_flag3 is null THEN
DBMS_OUTPUT.PUT_LINE(‘3’);
END IF;
END;