oracle编程基础语法

oracle数据开发

编程结构:

 declare
  [定义变量]
 begin
  [逻辑代码]
 exception
 [捕获异常]

 end;

 实例:
 declare
	a number:=1;
	b number:=2;
	c number;
 begin
 c:=(a*b)/(a+b);
 dbms_output.put_line(c);
 exception
  when zero_divide then
  dbms_output.put_line('除数不能为0');
  end;

变量:
  长度不能超过30个字符不能含有空格,表的字段长度也是;
  由字母、0-9数字、下划线、美元符号‘$’ 以及#号组成
  必须由字母开头
  关键字能作为变量,如if 等
  基础数据类型

实例:

param number default 104;



  %type变量
  %type是声明一个与指定的列名相同的数据类型;
  优点:用户不必查看表中的数据类型,即可确保数据类型与范围与表中的数据类型一致;
  如果对表中的数据结构修改,对编写的程序没有影响,程序的变量会随结构变化而变化
  缺点:执行的时候解析%type 需要查询数据词典,确定数据类型,可能会对性能产生影响

 

  实例:
  var_name emp.ename%type;


复合变量

 %rowtype变量;
 %rowtype声明一个与指定的表名相同的行类型;相当于定义一个和指定表相同的数据结构踢类型
  保存一行数据

 实例:
  row_employee emp%rowtype


 自定义变量:
  声明格式
  type record_name record(
file_name date_type [not null] [:=default_value],
...
  file_namen date_type [not null] [:=default_value]
  )
 根据用户需求定制数据变量,类似C语言的结构体
实例:
  type user_type record(
	user_no number,
	user_name nvarchar2(10)
  );
  user user_type;
 

分支

if..then.. 语句
  if 条件 then
  处理语句
  end if;
  
  
if..then.. 语句
  if 条件 then  处理语句  else 处理语句 end if;
  
 if..then.. 语句  

       if 条件 then 处理语句 

        elsif 处理语句
       else
     处理语句
      end if;
  
case条件语句
   case 
when 条件 then 处理语句;
when 条件 then 处理语句;
when 条件 then 处理语句;
  end;

if var_param > 0 then
dbms_output.put_line('var_param 的值大于0');
end if;


if var_param > 0 then
dbms_output.put_line('var_param 的值大于0');
else dbms_output.put_line('var_param 的值小于或等于0');
end if;


if var_param = 0 then
	dbms_output.put_line('var_param 的值等于0');
elsif var_param = 1  then 
	dbms_output.put_line('var_param 的值等于1');
else
	dbms_output.put_line('var_param 的值不等于1或0');
end if;

case 
when var_param = 0 then dbms_output.put_line('var_param 的值等于0');
when var_param = 1 then dbms_output.put_line('var_param 的值等于1');
when  var_param = 2  then dbms_output.put_line('var_param 的值等于2');
end



循环语句


  loop
处理语句
  exit when 退出循环条件
  end loop
  
  while 循环语句
  while 循环条件
  loop
   处理语句
   end loop;
   
   
   for循环
   for 变量 in 变量集合 loop
处理语句
   end loop;
   

loop 
var_param:=var_param+1 --自增
exit when  var_param>10 --当var_param的值大于10时推出循环
end loop;

while var_param <= 10   --当var_param的值小于等于10时进入循环
var_param:=var_param+1 --自增
end loop;

for var_param  in 1..10   --当var_param的值小于等于10时进入循环
loop
var_param:=var_param+1 --自增
end loop;



你可能感兴趣的:(oracle,编程,oracle)