频道栏目
首页 > 资讯 > Oracle > 正文

Oracle事物特性、什么是动态SQL?

17-10-30        来源:[db:作者]  
收藏   我要投稿

事物是作为单个逻辑工作单元执行的一系列操作 多个操作作为一个整体向系统提交,要么都执行,要么不执行 事物是一个不可分隔的工作逻辑单元 例:

事物的特性: 事物必须具有以下四个属性,简称ACID属性:

1.原子性

2.一致性

3.个理性

4.永久性

动态SQL

什么是动态SQL

编译期间SQL语句是不确定的,并且在运行时允许发生变化

动态SQL应用场合

要执行一个i额DDL语句时

需要增加程序的灵活性时

使用包DBMS_SQL动态执行SQL语句时

例:

动态SQL创建表

begin

execute immediate 'create table test_demo (id number primary key,uname varchar2(20) not null)';

end;

绑定变量

通过占位符绑定参数

参数类型可以是集合、对象等

不支持PL/SQL定义的类型

综合案例: 

--创建用户表tem_user

--编号:number类型 姓名:varchar2(20) 年龄:number

--若表存在请 先删除

--向表tem_user存入数据编号为1001、用户名“孙悟空”,年龄为30。

set serveroutput on;

declare

num binary_integer;

drop_sql VARCHAR2(100);

create_sql VARCHAR2(100);

insert_sql VARCHAR2(100);

id_v number :=1001;

name_v varchar2(20) :='孙悟空';

age_v number :=30;

begin

select count(*) into num from all_tables where table_name='tem_user';

if num>0

then

drop_sql:='drop table tem_user';

execute immediate drop_sql;

end if;

create_sql:='create table tem_user(id number primary key,name varchar2(20) not null,age number not null)';

execute immediate create_sql;

insert_sql:='insert into tem_user values (:1,:2,:3)';

execute immediate insert_sql using id_v,name_v,age_v;

COMMIT;

dbms_output.put_line('添加成功');

exception

when others then rollback;

dbms_output.put_line('添加失败');

end;

创建序列、使用、删除:

例:

--创建

create sequence seq_users

start with 1

increment by 1;

--使用

insert into users values(seq_users.nextval,'admin','123','男','123@qq.com');

--删除

drop sequence seq_users;

存储过程

预先存储好的SQL程序

保存在Oracle中

通过名称和参数执行

可带参数,也可返回结果

可包含数据操纵语句、变量、逻辑控制语句等

优点: 执行速度更快,减少网络流通量

定义存储过程的语法

存储过程的参数 参数可选, 参数可分为输入参数、输出参数

例:

--创建一个无参的存储过程

create or replace procedure hello_pro

as

begin

dbms_output.put_line('hello procedure');

end;

例:

--创建一个有参的存储过程

-- 1.参数的数据类型不能加长度

-- 2.不加in 或 out 默认就是in,即输入参数

-- 3.调用待用参数的存储过程,必须要传参

create or replace procedure with_param_pro(str in varchar2)

as

begin

dbms_output.put_line(str);

end;

综合练习:

例:通过编号查询员工姓名和工资

create or replace procedure emp_print_pro(eno emp.empno%type)

as

emp_ emp%rowtype;

begin

select * into emp_ from emp where empno=eno;

dbms_output.put_line('员工的姓名是'||emp_.ename||',基本工资是'||emp_.sal);

end;

--存储过程的执行方法:

set serveroutput on;

exec emp_print_pro(7499);

exec emp_print_pro(eno=>7788);

begin

emp_print_pro(7839);

end;

begin

emp_print_pro(eno=>7900);

end;

相关TAG标签
上一篇:如何查看db2表空间对应的物理文件?
下一篇:DB2 SQL0668N Operation not allowed for reason code "7" on table代码实例
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站