自学PL/SQL 第一讲decalring variables


  1.了解基本的PL/SQL块和结构
2.描述变量的在PL/SQL中的重要性
3.声明变量和执行PL/SQL块

一:PL/SQL的块结构

  
  
  
  
  1. DECLARE (Optional)  
  2.   Variables, cursors, user-defined exceptions  
  3. BEGIN (Mandatory)  
  4.   SQL statements  
  5.   PL/SQL statements  
  6. EXCEPTION (Optional)  
  7.   Actions to perform when errors occur  
  8. END; (Mandatory) 

 在begin区内的sql和pl/sql语句都需要以';'号结束,DECLARE,BEGIN,EXCEPTION关键字后面不需要跟';'号,END关键字则需要。PL/SQL的块类型主要有匿名(anonymous),过程(procedure)和函数(function),函数需要定义返回

二:变量的特点
Temporary storage of data
Manipulation of stored values
Reusability
Ease of maintenance

在PL/SQL中声明变量,可以在declare和begin区对变量进行声明,在begin区定义的变量可以覆盖之前定义的变量;变量的输出有IN,OUT,IN OUT三种类型
Declare and initialize variables in the declaration section.
Assign new values to variables in the executable section.
Pass values into PL/SQL blocks through parameters.
View results through output variables.

变量的类型:
PL/SQL variables
Non-PL/SQL variables: Bind and host variables(用在sqlplus和isqlplus环境下)
所有的PL/SQL变量都有相应的数据类型,数据类型指定存储格式,约束和可用的值范围;PL/SQL变量支持的数据类型有:scalar, composite, reference, LOB

三:声明变量
语法:identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr];
变量声明的指导原则
1.统一的命令规范,变量名尽量以v_开头,要避免变量名和字段名相同,否则变量将会优先被解释成字段运行
变量名不能超过30个字节,需要以字母开头
2.一行定义一个变量
3.需要初始化的变量定义not null和constant
4.对变量进行赋初始值使用':='或者default保留字

示例:

  
  
  
  
  1. SQL> set serveroutput on  
  2. SQL> declare  
  3.   2  v_hiredate DATE;  
  4.   3  v_deptno number(2) not null :=10;  
  5.   4  v_location varchar2(10) default 'fuzhou';  
  6.   5  c_comm constant number :1400;  
  7.   6  begin  
  8.   7  select hire_date into v_hiredate from hr.employees where employee_id=100;  
  9.   8  dbms_output.put_line('The hire_date is '||v_hiredate);  
  10.   9* end;  
  11. SQL> /  
  12. The hire_date is 1987-06-17-00:00:00   
  13. PL/SQL procedure successfully completed 

CONSTANT表示变量为固定变量,必须指定初始值;%TYPE属性可以指定变量的类型同基表的数据类型一致,这样可以避免将代码写死

绑定变量示例:调用绑定变量的时候需要加':'号

  
  
  
  
  1. SQL> variable v_salary number  
  2. SQL> begin  
  3.   2  select salary into :v_salary  
  4.   3  from hr.employees where employee_id=100;  
  5.   4  dbms_output.put_line('The result is '||:v_salary);  
  6.   5  end;  
  7.   6  /  
  8. The result is 100000  
  9. PL/SQL procedure successfully completed. 

替换变量示例:定义替换变量使用define命令,调用替换变量使用'&'符号

  
  
  
  
  1. SQL> define v_emp_id = 100 
  2. SQL> variable v_salary number  
  3. SQL> set verify off  
  4. SQL>  begin  
  5.   2  select salary into :v_salary  
  6.   3   from hr.employees where employee_id=&v_emp_id;  
  7.   4  dbms_output.put_line('The emp_id is '||&v_emp_id);  
  8.   5  dbms_output.put_line('The salary is '||:v_salary);  
  9.   6* end;  
  10. SQL> /  
  11. The emp_id is 100  
  12. The salary is 100000  
  13. PL/SQL procedure successfully completed. 

 

本文出自 “月牙天冲” 博客,谢绝转载!

  

你可能感兴趣的:(数据库,职场,休闲,好)