SQL Server "DROP TABLE 表名 CASCADE" 显示"CASCADE"附近有语法错误的原因

在学习数据库的过程中提到了使用CASCADE关键字来强制删除已被引用的关系(及其引用方)。

在实践过程中,使用SQL Server执行“ DROP TABLE Course CASCADE”却被提示有语法错误。

事实上报错的原因在于SQL Server不支持在删除过程中使用CASCADE关键字(见课本下图):


可看出SQL Server在删除表时并不区分RESTRICT或是CASCADE。

既然不支持,那为何又能识别CASCADE为关键字呢?

事实上在SQL Server中CASCADE关键字用于在建表操作时预先建立级联关系(通常和DENY关键字配合使用,所以报有语法错),建表后执行DROP操作时就不需要用户再指定删除模式了。


因此标题的那句“CASCADE”完全是用错了地方,应予以删除。

若因外键问题报错则应先将引用方删除或创建前使用CASCADE关键字确立级联关系。

  • 18
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Ø 常用查询 MySQL结束符是“;”结束。 1、 显示所有数据库 show databases; 2、 删除数据库 drop database dbName; 3、 创建数据库 create database [if not exists] dbName; 中括号部分可选的,判断该数据不存在就创建 4、 切换、使用指定数据库 use dbName; 5、 显示当前使用数据库所有的表对象 show tables; 6、 显示表结构describe(desc) desc tableName; 7、 创建一张表 create table user ( --int 整型 uId int, --小数 uPrice decimal, --普通长度文本,default设置默认值 uName varchar(255) default ‘zhangsan’, --超长文本 uRemark text, --图片 uPhoto blob, --日期 uBirthday datetime ); 8、 子查询建表方法 部分列名匹配模式: create table userInfo ( name varchar(20), sex char ) as select name, sex from user; 上面的列名和子查询的列名以及类型要对应 全部列名模式: create table userInfo as select * from user; 直接将整个表的类型和数据备份到新表userInfo中 9、 添加表字段 添加单列 alter table user add tel varchar(11) default ‘02012345678’; 添加多列 alter table user add ( photo blob, birthday date ); 上面就同时增加了多列字段 10、 修改表字段 修改tel列 alter table user modify tel varchar(15) default ‘02087654321’; 修改tel列的位置,在第一列显示 alter table user modify tel varchar(15) default '02087654321' first; 修改tel列的位置,在指定列之后显示 alter table user modify tel varchar(15) default '02087654321' after age; 注意:alter modify不支持一次修改多个列,但是Oracle支持多列修改 但是MySQL可以通过多个modify的方式完成: alter table user modify tel varchar(15) default '02087654321' first, modify name varchar(20) after tel; 11、 删除指定字段 alter table user drop photo; 12、 重命名表数据 表重命名 alter table user rename to users; 字段重命名 alter table users change name u_name varchar(10); alter table users change sex u_sex varchar(10) after u_name; 如果需要改变列名建议使用change,如果需要改变数据类型和显示位置可以使用modify 13、 删除表 drop table users; drop删除表会删除表结构,表对象将不存在数据中;数据也不会存在;表内的对象也不存在,如:索引、视图、约束; truncate删除表 truncate都被当成DDL出来,truncate的作用就是删除该表里的全部数据,保留表结构。相当于DDL中的delete语句, 但是truncate比delete语句的速度要快得多。但是truncate不能带条件删除指定数据,只会删除所有的数据。如果删除的表有外键, 删除的速度类似于delete。但新版本的MySQL中truncate的速度比delete速度快。 Ø 约束 MySQL中约束保存在information_schema数据库table_constraints中,可以通过该表查询约束信息; 约束主要完成对数据的检验,保证数据库数据的完整性;如果有相互依赖数据,保证该数据不被删除。 常用五类约束: not null:非空约束,指定某列不为空 unique: 唯一约束,指定某列和几列组合的数据不能重复 primary key:主键约束,指定某列的数据不能重复、唯一 foreign key:外键,指定该列记录属于主表中的一条记录,参照另一条数据 check:检查,指定一个表达式,用于检验指定数据 MySQL不支持check约束,但可以使用check约束,而没有任何效果; 根据约束数据列限制,约束可分为: 单列约束:每个约束只约束一列 多列约束:每个约束约束多列数据 MySQL中约束保存在information_schema数据库table_constraints中,可以通过该表查询约束信息; 1、 not null约束 非空约束用于确保当前列的值不为空值,非空约束只能出现在表对象的列上。 Null类型特征: 所有的类型的值都可以是null,包括int、float等数据类型 空字符串“”是不等于null,0也不等于null create table temp( id int not null, name varchar(255) not null default ‘abc’, sex char null ) 上面的table加上了非空约束,也可以用alter来修改或增加非空约束 增加非空约束 alter table temp modify sex varchar(2) not null; 取消非空约束 alter table temp modify sex varchar(2) null; 取消非空约束,增加默认值 alter table temp modify sex varchar(2) default ‘abc’ null; 2、 unique 唯一约束是指定table的列或列组合不能重复,保证数据的唯一性。虽然唯一约束不允许出现重复的值,但是可以为多个null 同一个表可以有多个唯一约束,多个列组合的约束。在创建唯一约束的时候,如果不给唯一约束名称,就默认和列名相同。 唯一约束不仅可以在一个表内创建,而且可以同时多表创建组合唯一约束。 MySQL会给唯一约束的列上默认创建一个唯一索引; create table temp ( id int not null, name varchar(25), password varchar(16), --使用表级约束语法, constraint uk_name_pwd unique(name, password) ); 表示用户名和密码组合不能重复 添加唯一约束 alter table temp add unique(name, password); alter table temp modify name varchar(25) unique; 删除约束 alter table temp drop index name; 3、 primary key 主键约束相当于唯一约束+非空约束的组合,主键约束列不允许重复,也不允许出现空值;如果的多列组合的主键约束, 那么这些列都不允许为空值,并且组合的值不允许重复。 每个表最多只允许一个主键,建立主键约束可以在列级别创建,也可以在表级别上创建。MySQL的主键名总是PRIMARY, 当创建主键约束时,系统默认会在所在的列和列组合上建立对应的唯一索引。 列模式: create table temp( /*主键约束*/ id int primary key, name varchar(25) ); create table temp2( id int not null, name varchar(25), pwd varchar(15), constraint pk_temp_id primary key(id) ); 组合模式: create table temp2( id int not null, name varchar(25), pwd varchar(15), constraint pk_temp_id primary key(name, pwd) ); alter删除主键约束 alter table temp drop primary key; alter添加主键 alter table temp add primary key(name, pwd); alter修改列为主键 alter table temp modify id int primary key; 设置主键自增 create table temp( id int auto_increment primary key, name varchar(20), pwd varchar(16) ); auto_increment自增模式,设置自增后在插入数据的时候就不需要给该列插入值了。 4、 foreign key 约束 外键约束是保证一个或两个表之间的参照完整性,外键是构建于一个表的两个字段或是两个表的两个字段之间的参照关系。 也就是说从表的外键值必须在主表中能找到或者为空。 当主表的记录被从表参照时,主表的记录将不允许删除,如果要删除数据,需要先删除从表中依赖该记录的数据, 然后才可以删除主表的数据。还有一种就是级联删除子表数据。 注意:外键约束的参照列,在主表中引用的只能是主键或唯一键约束的列,假定引用的主表列不是唯一的记录, 那么从表引用的数据就不确定记录的位置。同一个表可以有多个外键约束。 创建外键约束: 主表 create table classes( id int auto_increment primary key, name varchar(20) ); 从表 create table student( id int auto_increment, name varchar(22), constraint pk_id primary key(id), classes_id int references classes(id) ); 通常先建主表,然后再建从表,这样从表的参照引用的表才存在。 表级别创建外键约束: create table student( id int auto_increment primary key, name varchar(25), classes_id int, foreign key(classes_id) references classes(id) ); 上面的创建外键的方法没有指定约束名称,系统会默认给外键约束分配外键约束名称,命名为student_ibfk_n, 其中student是表名,n是当前约束从1开始的整数。 指定约束名称: create table student( id int auto_increment primary key, name varchar(25), classes_id int, /*指定约束名称*/ constraint fk_classes_id foreign key(classes_id) references classes(id) ); 多列外键组合,必须用表级别约束语法: create table classes( id int, name varchar(20), number int, primary key(name, number) ); create table student( id int auto_increment primary key, name varchar(20), classes_name varchar(20), classes_number int, /*表级别联合外键*/ foreign key(classes_name, classes_number) references classes(name, number) ); 删除外键约束: alter table student drop foreign key student_ibfk_1; alter table student drop foreign key fk_student_id; 增加外键约束 alter table student add foreign key(classes_name, classes_number) referencesclasses(name, number); 自引用、自关联(递归表、树状表) create table tree( id int auto_increment primary key, name varchar(50), parent_id int, foreign key(parent_id) references tree(id) ); 级联删除:删除主表的数据时,关联的从表数据也删除,则需要在建立外键约束的后面增加on deletecascade 或on delete set null,前者是级联删除,后者是将从表的关联列的值设置为null。 create table student( id int auto_increment primary key, name varchar(20), classes_name varchar(20), classes_number int, /*表级别联合外键*/ foreign key(classes_name, classes_number) references classes(name, number) on deletecascade ); 5、 check约束 MySQL可以使用check约束,但check约束对数据验证没有任何作用。 create table temp( id int auto_increment, name varchar(20), age int, primary key(id), /*check约束*/ check(age > 20) ); 上面check约束要求age必须大于0,但没有任何作用。但是创建table的时候没有任何错误或警告。 Ø 索引 索引是存放在模式(schema)中的一个数据库对象,索引的作用就是提高对表的检索查询速度, 索引是通过快速访问的方法来进行快速定位数据,从而减少了对磁盘的读写操作。 索引是数据库的一个对象,它不能独立存在,必须对某个表对象进行依赖。 提示:索引保存在information_schema数据库里的STATISTICS表中。 创建索引方式: 自动:当表上定义主键约束、唯一、外键约束时,该表会被系统自动添加上索引。 手动:手动在相关表或列上增加索引,提高查询速度。 删除索引方式: 自动:当表对象被删除时,该表上的索引自动被删除 手动:手动删除指定表对象的相关列上的索引 索引类似于书籍的目录,可以快速定位到相关的数据,一个表可以有多个索引。 创建索引: create index idx_temp_name on temp(name); 组合索引: create index idx_temp_name$pwd on temp(name, pwd); 删除索引: drop index idx_temp_name on temp; Ø 视图 视图就是一个表或多个表的查询结果,它是一张虚拟的表,因为它并不能存储数据。 视图的作用、优点: 限制对数据的访问 让复杂查询变得简单 提供数据的独立性 可以完成对相同数据的不同显示 创建、修改视图 create or replace view view_temp as select name, age from temp; 通常我们并不对视图的数据做修改操作,因为视图是一张虚拟的表,它并不存储实际数据。如果想让视图不被修改,可以用with check option来完成限制。 create or replace view view_temp as select * from temp with check option; 修改视图: alter view view_temp as select id, name from temp; 删除视图: drop view view_temp; 显示创建语法: show create view v_temp; Ø DML语句 DML主要针对数据库表对象的数据而言的,一般DML完成: 插入新数据 修改已添加的数据 删除不需要的数据 1、 insert into 插入语句 insert into temp values(null, ‘jack’, 25); 主键自增可以不插入,所以用null代替 指定列 insert into temp(name, age) values(‘jack’, 22); 在表面后面带括号,括号中写列名,values中写指定列名的值即可。当省略列名就表示插入全部数据, 注意插入值的顺序和列的顺序需要保持一致。 Set方式插入,也可以指定列 insert into temp set id = 7, name = 'jason'; MySQL中外键的table的外键引用列可以插入数据可以为null,不参照主表的数据。 使用子查询插入数据 insert into temp(name) select name from classes; 多行插入 insert into temp values(null, ‘jack’, 22), (null, ‘jackson’ 23); 2、 update 修改语句 update主要完成对数据的修改操作,可以修改一条或多条数据。修改多条或指定条件的数据,需要用where条件来完成。 修改所有数据 update temp set name = ‘jack2’; 所有的数据的name会被修改,如果修改多列用“,”分开 update temp set name = ‘jack’, age = 22; 修改指定条件的记录需要用where update temp set name = ‘jack’ where age > 22; 3、 delete 删除语句 删除table中的数据,可以删除所有,带条件可以删除指定的记录。 删除所有数据 delete from temp; 删除指定条件数据 delete from temp where age > 20; Ø select 查询、function 函数 select查询语句用得最广泛、功能也最丰富。可以完成单条记录、多条记录、单表、多表、子查询等。 1、 查询某张表所有数据 select * from temp; *代表所有列,temp代表表名,不带条件就查询所有数据 2、 查询指定列和条件的数据 select name, age from temp where age = 22; 查询name和age这两列,age 等于22的数据。 3、 对查询的数据进行运算操作 select age + 2, age / 2, age – 2, age * 2 from temp where age – 2 > 22; 4、 concat函数,字符串连接 select concat(name, ‘-eco’) from temp; concat和null进行连接,会导致连接后的数据成为null 5、 as 对列重命名 select name as ‘名称’ from temp; as也可以省略不写,效果一样 如果重命名的列名出现特殊字符,如“‘”单引号,那就需要用双引号引在外面 select name as “名’称” from temp; 6、 也可以给table去别名 select t.name Name from temp as t; 7、 查询常量 类似于SQL Server select 5 + 2; select concat('a', 'bbb'); 8、 distinct 去掉重复数据 select distinct id from temp; 多列将是组合的重复数据 select distinct id, age from temp; 9、 where 条件查询 大于>、大于等于>=、小于<、小于等于<=、等于=、不等于<> 都可以出现在where语句中 select * from t where a > 2 or a >= 3 or a < 5 or a <= 6 or a = 7 or a <> 0; 10、 and 并且 select * from temp where age > 20 and name = ‘jack’; 查询名称等于jack并且年龄大于20的 11、 or 或者 满足一个即可 select * from tmep where name = ‘jack’ or name = ‘jackson’; 12、 between v and v2 大于等于v且小于等于v2 select * form temp where age between 20 and 25; 13、 in 查询 可以多个条件 类似于or select * from temp where id in (1, 2, 3); 查询id在括号中出现的数据 14、 like 模糊查询 查询name以j开头的 select * from temp where name like ‘j%’; 查询name包含k的 select * from temp where name like ‘%k%’; escape转义 select * from temp where name like ‘/_%’ escape ‘/’; 指定/为转义字符,上面的就可以查询name中包含“_”的数据 15、 is null、is not null 查询为null的数据 select * from temp where name is null; 查询不为null的数据 select * from temp where name is not null; 16、 not select * from temp where not (age > 20); 取小于等于20的数据 select * from temp where id not in(1, 2); 17、 order by 排序,有desc、asc升序、降序 select * from temp order by id; 默认desc排序 select * from temp order by id asc; 多列组合 select * from temp order by id, age; Ø function 函数 函数的作用比较大,一般多用在select查询语句和where条件语句之后。按照函数返回的结果, 可以分为:多行函数和单行函数;所谓的单行函数就是将每条数据进行独立的计算,然后每条数据得到一条结果。 如:字符串函数;而多行函数,就是多条记录同时计算,得到最终只有一条结果记录。如:sum、avg等 多行函数也称为聚集函数、分组函数,主要用于完成一些统计功能。MySQL的单行函数有如下特征: 单行函数的参数可以是变量、常量或数据列。单行函数可以接受多个参数,但返回一个值。 单行函数就是它会对每一行单独起作用,每一行(可能包含多个参数)返回一个结果。 单行函数可以改变参数的数据类型。单行函数支持嵌套使用:内层函数的返回值是外层函数的参数。 单行函数可以分为: 类型转换函数; 位函数; 流程控制语句; 加密解密函数; 信息函数 单行函数 1、 char_length字符长度 select char_length(tel) from user; 2、 sin函数 select sin(age) from user; select sin(1.57); 3、 添加日期函数 select date_add('2010-06-21', interval 2 month); interval是一个关键字,2 month是2个月的意思,2是数值,month是单位 select addDate('2011-05-28', 2); 在前面的日期上加上后面的天数 4、 获取当前系统时间、日期 select curdate(); select curtime(); 5、 加密函数 select md5('zhangsan'); 6、 Null 处理函数 select ifnull(birthday, 'is null birthday') from user; 如果birthday为null,就返回后面的字符串 select nullif(age, 245) from user; 如果age等于245就返回null,不等就返回age select isnull(birthday) from user; 判断birthday是否为null select if(isnull(birthday), 'birthday is null', 'birthday not is null') from user; 如果birthday为null或是0就返回birthday is null,否则就返回birthday not is null;类似于三目运算符 7、 case 流程函数 case函数是一个流程控制函数,可以接受多个参数,但最终只会返回一个结果。 select name, age, (case sex when 1 then '男' when 0 then '女' else '火星人' end ) sex from user; 组函数 组函数就是多行函数,组函数是完成一行或多行结果集的运算,最后返回一个结果,而不是每条记录返回一个结果。 1、 avg平均值运算 select avg(age) from user; select avg(distinct age) from user; 2、 count 记录条数统计 select count(*), count(age), count(distinct age) from user; 3、 max 最大值 select max(age), max(distinct age) from user; 4、 min 最小值 select min(age), min(distinct age) from user; 5、 sum 求和、聚和 select sum(age), sum(distinct age) from user; select sum(ifnull(age, 0)) from user; 6、 group by 分组 select count(*), sex from user group by sex; select count(*) from user group by age; select * from user group by sex, age; 7、 having进行条件过滤 不能在where子句中过滤组,where子句仅用于过滤行。过滤group by需要having 不能在where子句中用组函数,having中才能用组函数 select count(*) from user group by sex having sex <> 2; Ø 多表查询和子查询 数据库的查询功能最为丰富,很多时候需要用到查询完成一些事物,而且不是单纯的对一个表进行操作。而是对多个表进行联合查询, MySQL中多表连接查询有两种规范,较早的SQL92规范支持,如下几种表连接查询: 等值连接 非等值连接 外连接 广义笛卡尔积 SQL99规则提供了可读性更好的多表连接语法,并提供了更多类型的连接查询,SQL99支持如下几种多表连接查询: 交叉连接 自然连接 使用using子句的连接 使用on子句连接 全部连接或者左右外连接 SQL92的连接查询 SQL92的连接查询语法比较简单,多将多个table放置在from关键字之后,多个table用“,”隔开; 连接的条件放在where条件之后,与查询条件直接用and逻辑运算符进行连接。如果条件中使用的是相等, 则称为等值连接,相反则称为非等值,如果没有任何条件则称为广义笛卡尔积。 广义笛卡尔积:select s.*, c.* from student s, classes c; 等值:select s.*, c.* from student s, classes c where s.cid = c.id; 非等值:select s.*, c.* from student s, classes c where s.cid <> c.id; select s.*, c.name classes from classes c, student s where c.id = s.classes_id ands.name is not null; SQL99连接查询 1、交叉连接cross join,类似于SQL92的笛卡尔积查询,无需条件。如: select s.*, c.name from student s cross join classes c; 2、自然连接 natural join查询,无需条件,默认条件是将2个table中的相同字段作为连接条件,如果没有相同字段,查询的结果就是空。 select s.*, c.name from student s natural join classes c; 3、using子句连接查询:using的子句可以是一列或多列,显示的指定两个表中同名列作为连接条件。 如果用natural join的连接查询,会把所有的相同字段作为连接查询。而using可以指定相同列及个数。 select s.*, c.name from student s join classes c using(id); 4、 join … on连接查询,查询条件在on中完成,每个on语句只能指定一个条件。 select s.*, c.name from student s join classes c on s.classes_id = c.id; 5、 左右外连接:3种外连接,left [outer] join、right [outer] join,连接条件都是通过用on子句来指定,条件可以等值、非等值。 select s.*, c.name from student s left join classes c on s.classes_id = c.id; select s.*, c.name from student s right join classes c on s.classes_id = c.id; 子查询 子查询就是指在查询语句中嵌套另一个查询,子查询可以支持多层嵌套。子查询可以出现在2个位置: from关键字之后,被当做一个表来进行查询,这种用法被称为行内视图,因为该子查询的实质就是一个临时视图 出现在where条件之后作为过滤条件的值 子查询注意点: 子查询用括号括起来,特别情况下需要起一个临时名称 子查询当做临时表时(在from之后的子查询),可以为该子查询起别名,尤其是要作为前缀来限定数据列名时 子查询用作过滤条件时,将子查询放在比较运算符的右边,提供可读性 子查询作为过滤条件时,单行子查询使用单行运算符,多行子查询用多行运算符 将from后面的子查询当做一个table来用: select * from (select id, name from classes) s where s.id in (1, 2); 当做条件来用: select * from student s where s.classes_id in (select id from classes); select * from student s where s.classes_id = any (select id from classes); select * from student s where s.classes_id > any (select id from classes); Ø 操作符和函数 1、 boolean只判断 select 1 is true, 0 is false, null is unknown; select 1 is not unknown, 0 is not unknown, null is not unknown; 2、 coalesce函数,返回第一个非null的值 select coalesce(null, 1); select coalesce(1, 1); select coalesce(null, 1); select coalesce(null, null); 3、 当有2个或多个参数时,返回最大的那个参数值 select greatest(2, 3); select greatest(2, 3, 1, 9, 55, 23); select greatest('D', 'A', 'B'); 4、 Least函数,返回最小值,如果有null就返回null值 select least(2, 0); select least(2, 0, null); select least(2, 10, 22.2, 35.1, 1.1); 5、 控制流函数 select case 1 when 1 then 'is 1' when 2 then 'is 2' else 'none' end; select case when 1 > 2 then 'yes' else 'no' end; 6、 ascii字符串函数 select ascii('A'); select ascii('1'); 7、 二进制函数 select bin(22); 8、 返回二进制字符串长度 select bit_length(11); 9、 char将值转换成字符,小数取整四舍五入 select char(65); select char(65.4); select char(65.5); select char(65.6); select char(65, 66, 67.4, 68.5, 69.6, '55.5', '97.3'); 10、 using改变字符集 select charset(char(0*65)), charset(char(0*65 using utf8)); 11、 得到字符长度char_length,character_length select char_length('abc'); select character_length('eft'); 12、 compress压缩字符串、uncompress解压缩 select compress('abcedf'); select uncompress(compress('abcedf')); 13、 concat_ws分隔字符串 select concat_ws('#', 'first', 'second', 'last'); select concat_ws('#', 'first', 'second', null, 'last'); Ø 事务处理 动作 开始事务:start transaction 提交事务:commit 回滚事务:rollback 设置自动提交:set autocommit 1 | 0 atuoCommit系统默认是1立即提交模式;如果要手动控制事务,需要设置set autoCommit 0; 这样我们就可以用commit、rollback来控制事务了。 在一段语句块中禁用autocommit 而不是set autocommit start transaction; select @result := avg(age) from temp; update temp set age = @result where id = 2; select * from temp where id = 2;//值被改变 rollback;//回滚 select * from temp where id = 2;//变回来了 在此期间只有遇到commit、rollback,start Transaction的禁用autocommit才会结束。然后就恢复到原来的autocommit模式; 不能回滚的语句 有些语句不能被回滚。通常,这些语句包括数据定义语言(DDL)语句,比如创建或取消数据库的语句, 和创建、取消或更改表或存储的子程序的语句。 您在设计事务时,不应包含这类语句。如果您在事务的前部中发布了一个不能被回滚的语句, 则后部的其它语句会发生错误,在这些情况下,通过发布ROLLBACK语句不能 回滚事务的全部效果。 一些操作也会隐式的提交事务 如alter、create、drop、rename table、lock table、set autocommit、starttransaction、truncate table 等等, 在事务中出现这些语句也会提交事务的 事务不能嵌套事务 事务的保存点 Savepoint pointName/Rollback to savepoint pointName 一个事务可以设置多个保存点,rollback可以回滚到指定的保存点,恢复保存点后面的操作。 如果有后面的保存点和前面的同名,则删除前面的保存点。 Release savepoint会删除一个保存点,如果在一段事务中执行commit或rollback,则事务结束,所以保存点删除。 Set Transaction设计数据库隔离级别 SET [GLOBAL | SESSION] TRANSACTION ISOLATION LEVEL { READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SERIALIZABLE } 本语句用于设置事务隔离等级,用于下一个事务,或者用于当前会话。 在默认情况下,SET TRANSACTION会为下一个事务(还未开始)设置隔离等级。 如果您使用GLOBAL关键词,则语句会设置全局性的默认事务等级, 用于从该点以后创建的所有新连接。原有的连接不受影响。使用SESSION关键测可以设置默认事务等级, 用于对当前连接执行的所有将来事务。 默认的等级是REPEATABLE READ全局隔离等级。 Ø 注释 select 1+1; # 单行注释 select 1+1; -- 单行注释 select 1 /* 多行注释 */ + 1; Ø 基本数据类型操作 字符串 select 'hello', '"hello"', '""hello""', 'hel''lo', '/'hello'; select "hello", "'hello'", "''hello''", "hel""lo", "/"hello"; /n换行 select 'This/nIs/nFour/nLines'; /转义 select 'hello / world!'; select 'hello /world!'; select 'hello // world!'; select 'hello /' world!'; Ø 设置数据库mode模式 SET sql_mode='ANSI_QUOTES'; create table t(a int); create table "tt"(a int); create table "t""t"(a int); craate talbe tab("a""b" int); Ø 用户变量 set @num1 = 0, @num2 = 2, @result = 0; select @result := (@num1 := 5) + @num2 := 3, @num1, @num2, @result; Ø 存储过程 创建存储过程: delimiter // create procedure get(out result int) begin select max(age) into result from temp; end// 调用存储过程: call get(@temp); 查询结果: select @temp; 删除存储过程: drop procedure get; 查看存储过程创建语句: show create procedure get; select…into 可以完成单行记录的赋值: create procedure getRecord(sid int) begin declare v_name varchar(20) default 'jason'; declare v_age int; declare v_sex bit; select name, age, sex into v_name, v_age, v_sex from temp where id = sid; select v_name, v_age, v_sex; end; call getRecord(1); Ø 函数 函数类似于存储过程,只是调用方式不同 例如:select max(age) from temp; 创建函数: create function addAge(age int) returns int return age + 5; 使用函数: select addAge(age) from temp; 删除函数: drop function if exists addAge; drop function addAge; 显示创建语法: show create function addAge; Ø 游标 声明游标:declare cur_Name cursor for select name from temp; 打开游标:open cur_Name; Fetch游标:fetch cur_Name into @temp; 关闭游标:close cur_Name; 示例: CREATE PROCEDURE cur_show() BEGIN DECLARE done INT DEFAULT 0; DECLARE v_id, v_age INT; DECLARE v_name varchar(20); DECLARE cur_temp CURSOR FOR SELECT id, name, age FROM temp; DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1; OPEN cur_temp; REPEAT FETCH cur_temp INTO v_id, v_name, v_age; IF NOT done THEN IF isnull(v_name) THEN update temp set name = concat('test-json', v_id) where id = v_id; ELSEIF isnull(v_age) THEN update temp set age = 22 where id = v_id; END IF; END IF; UNTIL done END REPEAT; CLOSE cur_temp; END Ø 触发器 触发器分为insert、update、delete三种触发器事件类型 还有after、before触发时间 创建触发器: create trigger trg_temp_ins before insert on temp for each row begin insert into temp_log values(NEW.id, NEW.name); end// 删除触发器: drop trigger trg_temp_ins
ORACLE常用命令 一、ORACLE的启动和关闭 1、在单机环境下 要想启动或关闭ORACLE系统必须首先切换到ORACLE用户,如下 su - oracle a、启动ORACLE系统 oracle>svrmgrl SVRMGR>connect internal SVRMGR>startup SVRMGR>quit b、关闭ORACLE系统 oracle>svrmgrl SVRMGR>connect internal SVRMGR>shutdown SVRMGR>quit 启动oracle9i数据库命令: $ sqlplus /nolog SQL*Plus: Release 9.2.0.1.0 - Production on Fri Oct 31 13:53:53 2003 Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved. SQL> connect / as sysdba Connected to an idle instance. SQL> startup^C SQL> startup ORACLE instance started. 2、在双机环境下 要想启动或关闭ORACLE系统必须首先切换到root用户,如下 su - root a、启动ORACLE系统 hareg -y oracle b、关闭ORACLE系统 hareg -n oracle Oracle数据库有哪几种启动方式 说明: 有以下几种启动方式: 1、startup nomount 非安装启动,这种方式启动下可执行:重建控制文件、重建数据库 读取init.ora文件,启动instance,即启动SGA和后台进程,这种启动只需要init.ora文件。 2、startup mount dbname 安装启动,这种方式启动下可执行: 数据库日志归档、 数据库介质恢复、 使数据文件联机或脱机, 重新定位数据文件、重做日志文件。 执行“nomount”,然后打开控制文件,确认数据文件和联机日志文件的位置, 但此时不对数据文件和日志文件进行校验检查。 3、startup open dbname 先执行“nomount”,然后执行“mount”,再打开包括Redo log文件在内的所有数据库文件, 这种方式下可访问数据库中的数据。 4、startup,等于以下三个命令 startup nomount alter database mount alter database open 5、startup restrict 约束方式启动 这种方式能够启动数据库,但只允许具有一定特权的用户访问 非特权用户访问时,会出现以下提示: ERROR: ORA-01035: ORACLE 只允许具有 RESTRICTED SESSION 权限的用户使用 6、startup force 强制启动方式 当不能关闭数据库时,可以用startup force来完成数据库的关闭 先关闭数据库,再执行正常启动数据库命令 7、startup pfile=参数文件名 带初始化参数文件的启动方式 先读取参数文件,再按参数文件中的设置启动数据库 例:startup pfile=E:Oracleadminoradbpfileinit.ora 8、startup EXCLUSIVE 二、用户如何有效地利用数据字典  ORACLE的数据字典是数据库的重要组成部分之一,它随着数据库的产生而产生, 随着数据库的变化而变化, 体现为sys用户下的一些表和视图。数据字典名称是大写的英文字符。 数据字典里存有用户信息、用户的权限信息、所有数据对象信息、表的约束条件、统计分析数据库的视图等。 我们不能手工修改数据字典里的信息。   很多时候,一般的ORACLE用户不知道如何有效地利用它。   dictionary   全部数据字典表的名称和解释,它有一个同义词dict dict_column   全部数据字典表里字段名称和解释 如果我们想查询跟索引有关的数据字典时,可以用下面这条SQL语句: SQL>select * from dictionary where instr(comments,'index')>0; 如果我们想知道user_indexes表各字段名称的详细含义,可以用下面这条SQL语句: SQL>select column_name,comments from dict_columns where table_name='USER_INDEXES'; 依此类推,就可以轻松知道数据字典的详细名称和解释,不用查看ORACLE的其它文档资料了。 下面按类别列出一些ORACLE用户常用数据字典的查询使用方法。 1、用户 查看当前用户的缺省表空间 SQL>select username,default_tablespace from user_users; 查看当前用户的角色 SQL>select * from user_role_privs; 查看当前用户的系统权限和表级权限 SQL>select * from user_sys_privs; SQL>select * from user_tab_privs; 2、表 查看用户下所有的表 SQL>select * from user_tables; 查看名称包含log字符的表 SQL>select object_name,object_id from user_objects where instr(object_name,'LOG')>0; 查看某表的创建时间 SQL>select object_name,created from user_objects where object_name=upper('&table_name'); 查看某表的大小 SQL>select sum(bytes)/(1024*1024) as "size(M)" from user_segments where segment_name=upper('&table_name'); 查看放在ORACLE的内存区里的表 SQL>select table_name,cache from user_tables where instr(cache,'Y')>0; 3、索引 查看索引个数和类别 SQL>select index_name,index_type,table_name from user_indexes order by table_name; 查看索引被索引的字段 SQL>select * from user_ind_columns where index_name=upper('&index_name'); 查看索引的大小 SQL>select sum(bytes)/(1024*1024) as "size(M)" from user_segments where segment_name=upper('&index_name'); 4、序列号 查看序列号,last_number是当前值 SQL>select * from user_sequences; 5、视图 查看视图的名称 SQL>select view_name from user_views; 查看创建视图的select语句 SQL>set view_name,text_length from user_views; SQL>set long 2000; 说明:可以根据视图的text_length值设定set long 的大小 SQL>select text from user_views where view_name=upper('&view_name'); 6、同义词 查看同义词的名称 SQL>select * from user_synonyms; 7、约束条件 查看某表的约束条件 SQL>select constraint_name, constraint_type,search_condition, r_constraint_name from user_constraints where table_name = upper('&table_name'); SQL>select c.constraint_name,c.constraint_type,cc.column_name from user_constraints c,user_cons_columns cc where c.owner = upper('&table_owner') and c.table_name = upper('&table_name') and c.owner = cc.owner and c.constraint_name = cc.constraint_name order by cc.position; 8、存储函数和过程 查看函数和过程的状态 SQL>select object_name,status from user_objects where object_type='FUNCTION'; SQL>select object_name,status from user_objects where object_type='PROCEDURE'; 查看函数和过程的源代码 SQL>select text from all_source where owner=user and name=upper('&plsql_name'); 三、查看数据库SQL 1、查看表空间的名称及大小 select t.tablespace_name, round(sum(bytes/(1024*1024)),0) ts_size from dba_tablespaces t, dba_data_files d where t.tablespace_name = d.tablespace_name group by t.tablespace_name; 2、查看表空间物理文件的名称及大小 select tablespace_name, file_id, file_name, round(bytes/(1024*1024),0) total_space from dba_data_files order by tablespace_name; 3、查看回滚段名称及大小 select segment_name, tablespace_name, r.status, (initial_extent/1024) InitialExtent,(next_extent/1024) NextExtent, max_extents, v.curext CurExtent From dba_rollback_segs r, v$rollstat v Where r.segment_id = v.usn(+) order by segment_name ; 4、查看控制文件 select name from v$controlfile; 5、查看日志文件 select member from v$logfile; 6、查看表空间的使用情况 select sum(bytes)/(1024*1024) as free_space,tablespace_name from dba_free_space group by tablespace_name; SELECT A.TABLESPACE_NAME,A.BYTES TOTAL,B.BYTES USED, C.BYTES FREE, (B.BYTES*100)/A.BYTES "% USED",(C.BYTES*100)/A.BYTES "% FREE" FROM SYS.SM$TS_AVAIL A,SYS.SM$TS_USED B,SYS.SM$TS_FREE C WHERE A.TABLESPACE_NAME=B.TABLESPACE_NAME AND A.TABLESPACE_NAME=C.TABLESPACE_NAME; 7、查看数据库库对象 select owner, object_type, status, count(*) count# from all_objects group by owner, object_type, status; 8、查看数据库的版本 Select version FROM Product_component_version Where SUBSTR(PRODUCT,1,6)='Oracle'; 9、查看数据库的创建日期和归档方式 Select Created, Log_Mode, Log_Mode From V$Database; 四、ORACLE用户连接的管理 用系统管理员,查看当前数据库有几个用户连接: SQL> select username,sid,serial# from v$session; 如果要停某个连接用 SQL> alter system kill session 'sid,serial#'; 如果这命令不行,找它UNIX的进程数 SQL> select pro.spid from v$session ses,v$process pro where ses.sid=21 and ses.paddr=pro.addr; 说明:21是某个连接的sid数 然后用 kill 命令杀此进程号。 五、SQL*PLUS使用 a、近入SQL*Plus $sqlplus 用户名/密码 退出SQL*Plus SQL>exit b、在sqlplus下得到帮助信息 列出全部SQL命令和SQL*Plus命令 SQL>help 列出某个特定的命令的信息 SQL>help 命令名 c、显示表结构命令DESCRIBE SQL>DESC 表名 d、SQL*Plus中的编辑命令 显示SQL缓冲区命令 SQL>L 修改SQL命令 首先要将待改正行变为当前行 SQL>n 用CHANGE命令修改内容 SQL>c/旧/新 重新确认是否已正确 SQL>L 使用INPUT命令可以在SQL缓冲区中增加一行或多行 SQL>i SQL>输入内容 e、调用外部系统编辑器 SQL>edit 文件名 可以使用DEFINE命令设置系统变量EDITOR来改变文本编辑器的类型,在login.sql文件中定义如下一行 DEFINE_EDITOR=vi f、运行命令文件 SQL>START test SQL>@test 常用SQL*Plus语句 a、表的创建、修改、删除 创建表的命令格式如下: create table 表名 (列说明列表); 为基表增加新列命令如下: ALTER TABLE 表名 ADD (列说明列表) 例:为test表增加一列Age,用来存放年龄 sql>alter table test add (Age number(3)); 修改基表列定义命令如下: ALTER TABLE 表名 MODIFY (列名 数据类型) 例:将test表中的Count列宽度加长为10个字符 sql>alter atble test modify (County char(10)); b、将一张表删除语句的格式如下: DORP TABLE 表名; 例:表删除将同时删除表的数据和表的定义 sql>drop table test c、表空间的创建、删除 六、ORACLE逻辑备份的SH文件 完全备份的SH文件:exp_comp.sh rq=` date +"%m%d" ` su - oracle -c "exp system/manager full=y inctype=complete file=/oracle/export/db_comp$rq.dmp" 累计备份的SH文件:exp_cumu.sh rq=` date +"%m%d" ` su - oracle -c "exp system/manager full=y inctype=cumulative file=/oracle/export/db_cumu$rq.dmp" 增量备份的SH文件: exp_incr.sh rq=` date +"%m%d" ` su - oracle -c "exp system/manager full=y inctype=incremental file=/oracle/export/db_incr$rq.dmp" root用户crontab文件 /var/spool/cron/crontabs/root增加以下内容 0 2 1 * * /oracle/exp_comp.sh 30 2 * * 0-5 /oracle/exp_incr.sh 45 2 * * 6 /oracle/exp_cumu.sh 当然这个时间表可以根据不同的需求来改变的,这只是一个例子。 七、ORACLE 常用的SQL语法和数据对象 一.数据控制语句 (DML) 部分 1.INSERT (往数据表里插入记录的语句) INSERT INTO 表名(字段名1, 字段名2, ……) VALUES ( 值1, 值2, ……); INSERT INTO 表名(字段名1, 字段名2, ……) SELECT (字段名1, 字段名2, ……) FROM 另外的表名; 字符串类型的字段值必须用单引号括起来, 例如: ’GOOD DAY’ 如果字段值里包含单引号’ 需要进行字符串转换, 我们把它替换成两个单引号''. 字符串类型的字段值超过定义的长度会出错, 最好在插入前进行长度校验. 日期字段的字段值可以用当前数据库的系统时间SYSDATE, 精确到秒 或者用字符串转换成日期型函数TO_DATE(‘2001-08-01’,’YYYY-MM-DD’) TO_DATE()还有很多种日期格式, 可以参看ORACLE DOC. 年-月-日 小时:分钟:秒 的格式YYYY-MM-DD HH24:MI:SS INSERT时最大可操作的字符串长度小于等于4000个单字节, 如果要插入更长的字符串, 请考虑字段用CLOB类型, 方法借用ORACLE里自带的DBMS_LOB程序包. INSERT时如果要用到从1开始自动增长的序列号, 应该先建立一个序列号 CREATE SEQUENCE 序列号的名称 (最好是表名+序列号标记) INCREMENT BY 1 START WITH 1 MAXVALUE 99999 CYCLE NOCACHE; 其中最大的值按字段的长度来定, 如果定义的自动增长的序列号 NUMBER(6) , 最大值为999999 INSERT 语句插入这个字段值为: 序列号的名称.NEXTVAL 2.DELETE (删除数据表里记录的语句) DELETE FROM表名 WHERE 条件; 注意:删除记录并不能释放ORACLE里被占用的数据块表空间. 它只把那些被删除的数据块标成unused. 如果确实要删除一个大表里的全部记录, 可以用 TRUNCATE 命令, 它可以释放占用的数据块表空间 TRUNCATE TABLE 表名; 此操作不可回退. 3.UPDATE (修改数据表里记录的语句) UPDATE表名 SET 字段名1=值1, 字段名2=值2, …… WHERE 条件; 如果修改的值N没有赋值或定义时, 将把原来的记录内容清为NULL, 最好在修改前进行非空校验; 值N超过定义的长度会出错, 最好在插入前进行长度校验.. 注意事项: A. 以上SQL语句对表都加上了行级锁, 确认完成后, 必须加上事物处理结束的命令 COMMIT 才能正式生效, 否则改变不一定写入数据库里. 如果想撤回这些操作, 可以用命令 ROLLBACK 复原. B. 在运行INSERT, DELETE 和 UPDATE 语句前最好估算一下可能操作的记录范围, 应该把它限定在较小 (一万条记录) 范围内,. 否则ORACLE处理这个事物用到很大的回退段. 程序响应慢甚至失去响应. 如果记录数上十万以上这些操作, 可以把这些SQL语句分段分次完成, 其间加上COMMIT 确认事物处理. 二.数据定义 (DDL) 部分 1.CREATE (创建表, 索引, 视图, 同义词, 过程, 函数, 数据库链接等) ORACLE常用的字段类型有 CHAR 固定长度的字符串 VARCHAR2 可变长度的字符串 NUMBER(M,N) 数字型M是位数总长度, N是小数的长度 DATE 日期类型 创建表时要把较小的不为空的字段放在前面, 可能为空的字段放在后面 创建表时可以用中文的字段名, 但最好还是用英文的字段名 创建表时可以给字段加上默认值, 例如 DEFAULT SYSDATE 这样每次插入和修改时, 不用程序操作这个字段都能得到动作的时间 创建表时可以给字段加上约束条件 例如 不允许重复 UNIQUE, 关键字 PRIMARY KEY 2.ALTER (改变表, 索引, 视图等) 改变表的名称 ALTER TABLE 表名1 TO 表名2; 在表的后面增加一个字段 ALTER TABLE表名 ADD 字段名 字段名描述; 修改表里字段的定义描述 ALTER TABLE表名 MODIFY字段名 字段名描述; 给表里的字段加上约束条件 ALTER TABLE 表名 ADD CONSTRAINT 约束名 PRIMARY KEY (字段名); ALTER TABLE 表名 ADD CONSTRAINT 约束名 UNIQUE (字段名); 把表放在或取出数据库的内存区 ALTER TABLE 表名 CACHE; ALTER TABLE 表名 NOCACHE; 3.DROP (删除表, 索引, 视图, 同义词, 过程, 函数, 数据库链接等) 删除表和它所有的约束条件 DROP TABLE 表名 CASCADE CONSTRAINTS; 4.TRUNCATE (清空表里的所有记录, 保留表的结构) TRUNCATE 表名; 三.查询语句 (SELECT) 部分 SELECT字段名1, 字段名2, …… FROM 表名1, [表名2, ……] WHERE 条件; 字段名可以带入函数 例如: COUNT(*), MIN(字段名), MAX(字段名), AVG(字段名), DISTINCT(字段名), TO_CHAR(DATE字段名,'YYYY-MM-DD HH24:MI:SS') NVL(EXPR1, EXPR2)函数 解释: IF EXPR1=NULL RETURN EXPR2 ELSE RETURN EXPR1 DECODE(AA﹐V1﹐R1﹐V2﹐R2....)函数 解释: IF AA=V1 THEN RETURN R1 IF AA=V2 THEN RETURN R2 ..… ELSE RETURN NULL LPAD(char1,n,char2)函数 解释: 字符char1按制定的位数n显示,不足的位数用char2字符串替换左边的空位 字段名之间可以进行算术运算 例如: (字段名1*字段名1)/3 查询语句可以嵌套 例如: SELECT …… FROM (SELECT …… FROM表名1, [表名2, ……] WHERE 条件) WHERE 条件2; 两个查询语句的结果可以做集合操作 例如: 并集UNION(去掉重复记录), 并集UNION ALL(不去掉重复记录), 差集MINUS, 交集INTERSECT 分组查询 SELECT字段名1, 字段名2, …… FROM 表名1, [表名2, ……] GROUP BY字段名1 [HAVING 条件] ; 两个以上表之间的连接查询 SELECT字段名1, 字段名2, …… FROM 表名1, [表名2, ……] WHERE 表名1.字段名 = 表名2. 字段名 [ AND ……] ; SELECT字段名1, 字段名2, …… FROM 表名1, [表名2, ……] WHERE 表名1.字段名 = 表名2. 字段名(+) [ AND ……] ; 有(+)号的字段位置自动补空值 查询结果集的排序操作, 默认的排序是升序ASC, 降序是DESC SELECT字段名1, 字段名2, …… FROM 表名1, [表名2, ……] ORDER BY字段名1, 字段名2 DESC; 字符串模糊比较的方法 INSTR(字段名, ‘字符串’)>0 字段名 LIKE ‘字符串%’ [‘%字符串%’] 每个表都有一个隐含的字段ROWID, 它标记着记录的唯一性. 四.ORACLE里常用的数据对象 (SCHEMA) 1.索引 (INDEX) CREATE INDEX 索引名ON 表名 ( 字段1, [字段2, ……] ); ALTER INDEX 索引名 REBUILD; 一个表的索引最好不要超过三个 (特殊的大表除外), 最好用单字段索引, 结合SQL语句的分析执行情况, 也可以建立多字段的组合索引和基于函数的索引 ORACLE8.1.7字符串可以索引的最大长度为1578 单字节 ORACLE8.0.6字符串可以索引的最大长度为758 单字节 2.视图 (VIEW) CREATE VIEW 视图名AS SELECT …. FROM …..; ALTER VIEW视图名 COMPILE; 视图仅是一个SQL查询语句, 它可以把表之间复杂的关系简洁化. 3.同义词 (SYNONMY) CREATE SYNONYM同义词名FOR 表名; CREATE SYNONYM同义词名FOR 表名@数据库链接名; 4.数据库链接 (DATABASE LINK) CREATE DATABASE LINK数据库链接名CONNECT TO 用户名 IDENTIFIED BY 密码 USING ‘数据库连接字符串’; 数据库连接字符串可以用NET8 EASY CONFIG或者直接修改TNSNAMES.ORA里定义. 数据库参数global_name=true时要求数据库链接名称跟远端数据库名称一样 数据库全局名称可以用以下命令查出 SELECT * FROM GLOBAL_NAME; 查询远端数据库里的表 SELECT …… FROM 表名@数据库链接名; 五.权限管理 (DCL) 语句 1.GRANT 赋于权限 常用的系统权限集合有以下三个: CONNECT(基本的连接), RESOURCE(程序开发), DBA(数据库管理) 常用的数据对象权限有以下五个: ALL ON 数据对象名, SELECT ON 数据对象名, UPDATE ON 数据对象名, DELETE ON 数据对象名, INSERT ON 数据对象名, ALTER ON 数据对象名 GRANT CONNECT, RESOURCE TO 用户名; GRANT SELECT ON 表名 TO 用户名; GRANT SELECT, INSERT, DELETE ON表名 TO 用户名1, 用户名2; 2.REVOKE 回收权限 REVOKE CONNECT, RESOURCE FROM 用户名; REVOKE SELECT ON 表名 FROM 用户名; REVOKE SELECT, INSERT, DELETE ON表名 FROM 用户名1, 用户名2; 查询数据库中第63号错误: select orgaddr,destaddr from sm_histable0116 where error_code='63'; 查询数据库中开户用户最大提交和最大下发数: select MSISDN,TCOS,OCOS from ms_usertable; 查询数据库中各种错误代码的总和: select error_code,count(*) from sm_histable0513 group by error_code order by error_code; 查询报表数据库中话单统计种类查询。 select sum(Successcount) from tbl_MiddleMt0411 where ServiceType2=111 select sum(successcount),servicetype from tbl_middlemt0411 group by servicetype 原文地址:http://www.cnoug.org/viewthread.php?tid=60293 //创建一个控制文件命令到跟踪文件 alter database backup controlfile to trace; //增加一个新的日志文件组的语句 connect internal as sysdba alter database add logfile group 4 (’/db01/oracle/CC1/log_1c.dbf’, ’/db02/oracle/CC1/log_2c.dbf’) size 5M; alter database add logfile member ’/db03/oracle/CC1/log_3c.dbf’ to group 4; //在Server Manager上MOUNT并打开一个数据库: connect internal as sysdba startup mount ORA1 exclusive; alter database open; //生成数据字典 @catalog @catproc //在init.ora 中备份数据库的位置 log_archive_dest_1 = ’/db00/arch’ log_archive_dest_state_1 = enable log_archive_dest_2 = "service=stby.world mandatory reopen=60" log_archive_dest_state_2 = enable //对用户的表空间的指定和管理相关的语句 create user USERNAME identified by PASSWORD default tablespace TABLESPACE_NAME; alter user USERNAME default tablespace TABLESPACE_NAME; alter user SYSTEM quota 0 on SYSTEM; alter user SYSTEM quota 50M on TOOLS; create user USERNAME identified by PASSWORD default tablespace DATA temporary tablespace TEMP; alter user USERNAME temporary tablespace TEMP; //重新指定一个数据文件的大小 : alter database datafile ’/db05/oracle/CC1/data01.dbf’ resize 200M; //创建一个自动扩展的数据文件: create tablespace DATA datafile ’/db05/oracle/CC1/data01.dbf’ size 200M autoextend ON next 10M maxsize 250M; //在表空间上增加一个自动扩展的数据文件: alter tablespace DATA add datafile ’/db05/oracle/CC1/data02.dbf’ size 50M autoextend ON maxsize 300M; //修改参数: alter database datafile ’/db05/oracle/CC1/data01.dbf’ autoextend ON maxsize 300M; //在数据文件移动期间重新命名: alter database rename file ’/db01/oracle/CC1/data01.dbf’ to ’/db02/oracle/CC1/data01.dbf’; alter tablespace DATA rename datafile ’/db01/oracle/CC1/data01.dbf’ to ’/db02/oracle/CC1/data01.dbf’; alter database rename file ’/db05/oracle/CC1/redo01CC1.dbf’ to ’/db02/oracle/CC1/redo01CC1.dbf’; alter database datafile ’/db05/oracle/CC1/data01.dbf’ resize 80M; //创建和使用角色: create role APPLICATION_USER; grant CREATE SESSION to APPLICATION_USER; grant APPLICATION_USER to username; //回滚段的管理 create rollback segment SEGMENT_NAME tablespace RBS; alter rollback segment SEGMENT_NAME offline; drop rollback segment SEGMENT_NAME; alter rollback segment SEGMENT_NAME online; //回滚段上指定事务 commit; set transaction use rollback segment ROLL_BATCH; insert into TABLE_NAME select * from DATA_LOAD_TABLE; commit; //查询回滚段的 大小和优化参数 select * from DBA_SEGMENTS where Segment_Type = ’ROLLBACK’; select N.Name, /* rollback segment name */ S.OptSize /* rollback segment OPTIMAL size */ from V$ROLLNAME N, V$ROLLSTAT S where N.USN=S.USN; //回收回滚段 alter rollback segment R1 shrink to 15M; alter rollback segment R1 shrink; //例子 set transaction use rollback segment SEGMENT_NAME alter tablespace RBS default storage (initial 125K next 125K minextents 18 maxextents 249) create rollback segment R4 tablespace RBS storage (optimal 2250K); alter rollback segment R4 online; select Sessions_Highwater from V$LICENSE; grant select on EMPLOYEE to PUBLIC; //用户和角色 create role ACCOUNT_CREATOR; grant CREATE SESSION, CREATE USER, ALTER USER to ACCOUNT_CREATOR; alter user THUMPER default role NONE; alter user THUMPER default role CONNECT; alter user THUMPER default role all except ACCOUNT_CREATOR; alter profile DEFAULT limit idle_time 60; create profile LIMITED_PROFILE limit FAILED_LOGIN_ATTEMPTS 5; create user JANE identified by EYRE profile LIMITED_PROFILE; grant CREATE SESSION to JANE; alter user JANE account unlock; alter user JANE account lock; alter profile LIMITED_PROFILE limit PASSWORD_LIFE_TIME 30; alter user jane password expire; //创建操作系统用户 REM Creating OPS$ accounts create user OPS$FARMER identified by SOME_PASSWORD default tablespace USERS temporary tablespace TEMP; REM Using identified externally create user OPS$FARMER identified externally default tablespace USERS temporary tablespace TEMP; //执行ORAPWD ORAPWD FILE=filename PASSWORD=password ENTRIES=max_users create role APPLICATION_USER; grant CREATE SESSION to APPLICATION_USER; create role DATA_ENTRY_CLERK; grant select, insert on THUMPER.EMPLOYEE to DATA_ENTRY_CLERK; grant select, insert on THUMPER.TIME_CARDS to DATA_ENTRY_CLERK; grant select, insert on THUMPER.DEPARTMENT to DATA_ENTRY_CLERK; grant APPLICATION_USER to DATA_ENTRY_CLERK; grant DATA_ENTRY_CLERK to MCGREGOR; grant DATA_ENTRY_CLERK to BPOTTER with admin option; //设置角色 set role DATA_ENTRY_CLERK; set role NONE; //回收权利: revoke delete on EMPLOYEE from PETER; revoke all on EMPLOYEE from MCGREGOR; //回收角色: revoke ACCOUNT_CREATOR from HELPDESK; drop user USERNAME cascade; grant SELECT on EMPLOYEE to MCGREGOR with grant option; grant SELECT on THUMPER.EMPLOYEE to BPOTTER with grant option; revoke SELECT on EMPLOYEE from MCGREGOR; create user MCGREGOR identified by VALUES ’1A2DD3CCEE354DFA’; alter user OPS$FARMER identified by VALUES ’no way’; //备份与恢复 使用 export 程序 exp system/manager file=expdat.dmp compress=Y owner=(HR,THUMPER) exp system/manager file=hr.dmp owner=HR indexes=Y compress=Y imp system/manager file=hr.dmp full=Y buffer=64000 commit=Y //备份表 exp system/manager FILE=expdat.dmp TABLES=(Thumper.SALES) //备份分区 exp system/manager FILE=expdat.dmp TABLES=(Thumper.SALES:Part1) //输入例子 imp system/manager file=expdat.dmp imp system/manager file=expdat.dmp buffer=64000 commit=Y exp system/manager file=thumper.dat owner=thumper grants=N indexes=Y compress=Y rows=Y imp system/manager file=thumper.dat FROMUSER=thumper TOUSER=flower rows=Y indexes=Y imp system/manager file=expdat.dmp full=Y commit=Y buffer=64000 imp system/manager file=expdat.dmp ignore=N rows=N commit=Y buffer=64000 //使用操作系统备份命令 REM TAR examples tar -cvf /dev/rmt/0hc /db0[1-9]/oracle/CC1 tar -rvf /dev/rmt/0hc /orasw/app/oracle/CC1/pfile/initcc1.ora tar -rvf /dev/rmt/0hc /db0[1-9]/oracle/CC1 /orasw/app/oracle/CC1/pfile/initcc1.ora //离线备份的shell脚本 ORACLE_SID=cc1; export ORACLE_SID ORAENV_ASK=NO; export ORAENV_ASK . oraenv svrmgrl <<EOF1 connect internal as sysdba shutdown immediate; exit EOF1 insert backup commands like the "tar" commands here svrmgrl <<EOF2 connect internal as sysdba startup EOF2 //在Server Manager上设置为archivelog mode: connect internal as sysdba startup mount cc1; alter database archivelog; archive log start; alter database open; //在Server Manager上设置为archivelog mode: connect internal as sysdba startup mount cc1; alter database noarchivelog; alter database open; select Name, Value from V$PARAMETER where Name like ’log_archive%’; //联机备份的脚本 # # Sample Hot Backup Script for a UNIX File System database # # Set up environment variables: ORACLE_SID=cc1; export ORACLE_SID ORAENV_ASK=NO; export ORAENV_ASK . oraenv svrmgrl <<EOFarch1 connect internal as sysdba REM REM 备份 SYSTEM tablespace REM alter tablespace SYSTEM begin backup; !tar -cvf /dev/rmt/0hc /db01/oracle/CC1/sys01.dbf alter tablespace SYSTEM end backup; REM REM The SYSTEM tablespace has now been written to a REM tar saveset on the tape device /dev/rmt/0hc. The REM rest of the tars must use the "-rvf" clause to append REM to that saveset. REM REM 备份 RBS tablespace REM alter tablespace RBS begin backup; !tar -rvf /dev/rmt/0hc /db02/oracle/CC1/rbs01.dbf alter tablespace RBS end backup; REM REM 备份 DATA tablespace REM For the purposes of this example, this tablespace REM will contain two files, data01.dbf and data02.dbf. REM The * wildcard will be used in the filename. REM alter tablespace DATA begin backup; !tar -rvf /dev/rmt/0hc /db03/oracle/CC1/data0*.dbf alter tablespace DATA end backup; REM REM 备份 INDEXES tablespace REM alter tablespace INDEXES begin backup; !tar -rvf /dev/rmt/0hc /db04/oracle/CC1/indexes01.dbf alter tablespace INDEXES end backup; REM REM 备份 TEMP tablespace REM alter tablespace TEMP begin backup; !tar -rvf /dev/rmt/0hc /db05/oracle/CC1/temp01.dbf alter tablespace TEMP end backup; REM REM Follow the same pattern to back up the rest REM of the tablespaces. REM REM REM Step 2. 备份归档日志文件. archive log stop REM REM Exit Server Manager, using the indicator set earlier. exit EOFarch1 # # Record which files are in the destination directory. # Do this by setting an environment variable that is # equal to the directory listing for the destination # directory. # For this example, the log_archive_dest is # /db01/oracle/arch/CC1. # FILES=`ls /db01/oracle/arch/CC1/arch*.dbf`; export FILES # # Now go back into Server Manager and restart the # archiving process. Set an indicator (called EOFarch2 # in this example). # svrmgrl <<EOFarch2 connect internal archive log start; exit EOFarch2 # # Now back up the archived redo logs to the tape # device via the "tar" command, then delete them # from the destination device via the "rm" command. # You may choose to compress them instead. # tar -rvf /dev/rmt/0hc $FILES rm -f $FILES # # Step 3. 备份控制文件到磁盘. # svrmgrl <<EOFarch3 connect internal alter database backup controlfile to ’db01/oracle/CC1/CC1controlfile.bck’; exit EOFarch3 # # 备份控制文件到磁带. # tar -rvf /dev/rmt/0hc /db01/oracle/CC1/CC1controlfile.bck # # End of hot backup script. //自动生成开始备份的脚本 set pagesize 0 feedback off select ’alter tablespace ’||Tablespace_Name||’ begin backup;’ from DBA_TABLESPACES where Status ’INVALID’ spool alter_begin.sql / spool off //自动生成备份结束的脚本 set pagesize 0 feedback off select ’alter tablespace ’||Tablespace_Name||’ end backup;’ from DBA_TABLESPACES where Status ’INVALID’ spool alter_end.sql / spool off //备份归档日志文件的脚本. REM See text for alternatives. # Step 1: Stop the archiving process. This will keep # additional archived redo log files from being written # to the destination directory during this process. # svrmgrl <<EOFarch1 connect internal as sysdba archive log stop; REM REM Exit Server Manager using the indicator set earlier. exit EOFarch1 # # Step 2: Record which files are in the destination # directory. # Do this by setting an environment variable that is # equal to the directory listing for the destination # directory. # For this example, the log_archive_dest is # /db01/oracle/arch/CC1. # FILES=`ls /db01/oracle/arch/CC1/arch*.dbf`; export FILES # # Step 3: Go back into Server Manager and restart the # archiving process. Set an indicator (called EOFarch2 # in this example). # svrmgrl <<EOFarch2 connect internal as sysdba archive log start; exit EOFarch2 # # Step 4. Back up the archived redo logs to the tape # device via the "tar" command, then delete them # from the destination device via the "rm" command. # tar -rvf /dev/rmt/0hc $FILES # # Step 5. Delete those files from the destination directory. # rm -f $FILES # # End of archived redo log file backup script. REM 磁盘到磁盘的备份 REM REM Back up the RBS tablespace - to another disk (UNIX) REM alter tablespace RBS begin backup; !cp /db02/oracle/CC1/rbs01.dbf /db10/oracle/CC1/backups alter tablespace RBS end backup; REM REM 移动归档日志文件的shell脚本 # # Procedure for moving archived redo logs to another device # svrmgrl <<EOFarch2 connect internal as sysdba archive log stop; !mv /db01/oracle/arch/CC1 /db10/oracle/arch/CC1 archive log start; exit EOFarch2 # # end of archived redo log directory move. //生成创建控制文件命令 alter database backup controlfile to trace; //时间点恢复的例子 connect internal as sysdba startup mount instance_name; recover database until time ’1999-08-07:14:40:00’; //创建恢复目录 rman rcvcat rman/rman@ // 在(UNIX)下创建恢复目录 RMAN> create catalog tablespace rcvcat; // 在(NT)下创建恢复目录 RMAN> create catalog tablespace "RCVCAT"; //连接描述符范例 (DESCRIPTION= (ADDRESS= (PROTOCOL=TCP) (HOST=HQ) (PORT=1521)) (CONNECT DATA= (SID=loc))) // listener.ora 的条目entry // listener.ora 的条目entry LISTENER = (ADDRESS_LIST = (ADDRESS= (PROTOCOL=IPC) (KEY= loc.world) ) ) SID_LIST_LISTENER = (SID_LIST = (SID_DESC = (SID_NAME = loc) (ORACLE_HOME = /orasw/app/oracle/product/8.1.5.1) ) ) // tnsnames.ora 的条目 LOC= (DESCRIPTION= (ADDRESS = (PROTOCOL = TCP) (HOST = HQ) (PORT = 1521)) ) (CONNECT_DATA = (SERVICE_NAME = loc) (INSTANCE_NAME = loc) ) ) //连接参数的设置(sql*net) LOC =(DESCRIPTION= (ADDRESS= (COMMUNITY=TCP.HQ.COMPANY) (PROTOCOL=TCP) (HOST=HQ) (PORT=1521)) (CONNECT DATA= (SID=loc))) //参数文件配置范例 // tnsnames.ora HQ =(DESCRIPTION= (ADDRESS= (PROTOCOL=TCP) (HOST=HQ) (PORT=1521)) (CONNECT DATA= (SID=loc))) // listener.ora LISTENER = (ADDRESS_LIST = (ADDRESS= (PROTOCOL=IPC) (KEY= loc) ) ) SID_LIST_LISTENER = (SID_LIST = (SID_DESC = (SID_NAME = loc) (ORACLE_HOME = /orasw/app/oracle/product/8.1.5.1) ) ) // Oracle8I tnsnames.ora LOC= (DESCRIPTION= (ADDRESS = (PROTOCOL = TCP) (HOST = HQ) (PORT = 1521)) ) (CONNECT_DATA = (SERVICE_NAME = loc) (INSTANCE_NAME = loc) ) ) //使用 COPY 实现数据库之间的复制 copy from remote_username/remote_password@service_name to username/password@service_name [append|create|insert|replace] TABLE_NAME using subquery; REM COPY example set copycommit 1 set arraysize 1000 copy from HR/PUFFINSTUFF@loc - create EMPLOYEE - using - select * from EMPLOYEE //监视器的管理 lsnrctl start lsnrctl start my_lsnr lsnrctl status lsnrctl status hq 检查监视器的进程 ps -ef | grep tnslsnr //在 lsnrctl 内停止监视器 set password lsnr_password stop //在lsnrctl 内列出所有的服务 set password lsnr_password services //启动或停止一个NT的listener net start OracleTNSListener net stop OracleTNSListener // tnsnames.ora 文件的内容 fld1 = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP) (HOST = server1.fld.com)(PORT = 1521)) ) (CONNECT_DATA = (SID = fld1) ) ) //操作系统网络的管理 telnet host_name ping host_name /etc/hosts 文件 130.110.238.109 nmhost 130.110.238.101 txhost 130.110.238.102 azhost arizona //oratab 表项 loc:/orasw/app/oracle/product/8.1.5.1:Y cc1:/orasw/app/oracle/product/8.1.5.1:N old:/orasw/app/oracle/product/8.1.5.0:Y //创建一个控制文件命令到跟踪文件 alter database backup controlfile to trace; //增加一个新的日志文件组的语句 connect internal as sysdba alter database add logfile group 4 (’/db01/oracle/CC1/log_1c.dbf’, ’/db02/oracle/CC1/log_2c.dbf’) size 5M; alter database add logfile member ’/db03/oracle/CC1/log_3c.dbf’ to group 4; //在Server Manager上MOUNT并打开一个数据库: connect internal as sysdba startup mount ORA1 exclusive; alter database open; //生成数据字典 @catalog @catproc //在init.ora 中备份数据库的位置 log_archive_dest_1 = ’/db00/arch’ log_archive_dest_state_1 = enable log_archive_dest_2 = "service=stby.world mandatory reopen=60" log_archive_dest_state_2 = enable //对用户的表空间的指定和管理相关的语句 create user USERNAME identified by PASSWORD default tablespace TABLESPACE_NAME; alter user USERNAME default tablespace TABLESPACE_NAME; alter user SYSTEM quota 0 on SYSTEM; alter user SYSTEM quota 50M on TOOLS; create user USERNAME identified by PASSWORD default tablespace DATA temporary tablespace TEMP; alter user USERNAME temporary tablespace TEMP; //重新指定一个数据文件的大小 : alter database datafile ’/db05/oracle/CC1/data01.dbf’ resize 200M; //创建一个自动扩展的数据文件: create tablespace DATA datafile ’/db05/oracle/CC1/data01.dbf’ size 200M autoextend ON next 10M maxsize 250M; //在表空间上增加一个自动扩展的数据文件: alter tablespace DATA add datafile ’/db05/oracle/CC1/data02.dbf’ size 50M autoextend ON maxsize 300M; //修改参数: alter database datafile ’/db05/oracle/CC1/data01.dbf’ autoextend ON maxsize 300M; //在数据文件移动期间重新命名: alter database rename file ’/db01/oracle/CC1/data01.dbf’ to ’/db02/oracle/CC1/data01.dbf’; alter tablespace DATA rename datafile ’/db01/oracle/CC1/data01.dbf’ to ’/db02/oracle/CC1/data01.dbf’; alter database rename file ’/db05/oracle/CC1/redo01CC1.dbf’ to ’/db02/oracle/CC1/redo01CC1.dbf’; alter database datafile ’/db05/oracle/CC1/data01.dbf’ resize 80M; //创建和使用角色: create role APPLICATION_USER; grant CREATE SESSION to APPLICATION_USER; grant APPLICATION_USER to username; //回滚段的管理 create rollback segment SEGMENT_NAME tablespace RBS; alter rollback segment SEGMENT_NAME offline; drop rollback segment SEGMENT_NAME; alter rollback segment SEGMENT_NAME online; //回滚段上指定事务 commit; set transaction use rollback segment ROLL_BATCH; insert into TABLE_NAME select * from DATA_LOAD_TABLE; commit; //查询回滚段的 大小和优化参数 select * from DBA_SEGMENTS where Segment_Type = ’ROLLBACK’; select N.Name, /* rollback segment name */ S.OptSize /* rollback segment OPTIMAL size */ from V$ROLLNAME N, V$ROLLSTAT S where N.USN=S.USN; //回收回滚段 alter rollback segment R1 shrink to 15M; alter rollback segment R1 shrink; //例子 set transaction use rollback segment SEGMENT_NAME alter tablespace RBS default storage (initial 125K next 125K minextents 18 maxextents 249) create rollback segment R4 tablespace RBS storage (optimal 2250K); alter rollback segment R4 online; select Sessions_Highwater from V$LICENSE; grant select on EMPLOYEE to PUBLIC; //用户和角色 create role ACCOUNT_CREATOR; grant CREATE SESSION, CREATE USER, ALTER USER to ACCOUNT_CREATOR; alter user THUMPER default role NONE; alter user THUMPER default role CONNECT; alter user THUMPER default role all except ACCOUNT_CREATOR; alter profile DEFAULT limit idle_time 60; create profile LIMITED_PROFILE limit FAILED_LOGIN_ATTEMPTS 5; create user JANE identified by EYRE profile LIMITED_PROFILE; grant CREATE SESSION to JANE; alter user JANE account unlock; alter user JANE account lock; alter profile LIMITED_PROFILE limit PASSWORD_LIFE_TIME 30; alter user jane password expire; //创建操作系统用户 REM Creating OPS$ accounts create user OPS$FARMER identified by SOME_PASSWORD default tablespace USERS temporary tablespace TEMP; REM Using identified externally create user OPS$FARMER identified externally default tablespace USERS temporary tablespace TEMP; //执行ORAPWD ORAPWD FILE=filename PASSWORD=password ENTRIES=max_users create role APPLICATION_USER; grant CREATE SESSION to APPLICATION_USER; create role DATA_ENTRY_CLERK; grant select, insert on THUMPER.EMPLOYEE to DATA_ENTRY_CLERK; grant select, insert on THUMPER.TIME_CARDS to DATA_ENTRY_CLERK; grant select, insert on THUMPER.DEPARTMENT to DATA_ENTRY_CLERK; grant APPLICATION_USER to DATA_ENTRY_CLERK; grant DATA_ENTRY_CLERK to MCGREGOR; grant DATA_ENTRY_CLERK to BPOTTER with admin option; //设置角色 set role DATA_ENTRY_CLERK; set role NONE; //回收权利: revoke delete on EMPLOYEE from PETER; revoke all on EMPLOYEE from MCGREGOR; //回收角色: revoke ACCOUNT_CREATOR from HELPDESK; drop user USERNAME cascade; grant SELECT on EMPLOYEE to MCGREGOR with grant option; grant SELECT on THUMPER.EMPLOYEE to BPOTTER with grant option; revoke SELECT on EMPLOYEE from MCGREGOR; create user MCGREGOR identified by VALUES ’1A2DD3CCEE354DFA’; alter user OPS$FARMER identified by VALUES ’no way’; //备份与恢复 使用 export 程序 exp system/manager file=expdat.dmp compress=Y owner=(HR,THUMPER) exp system/manager file=hr.dmp owner=HR indexes=Y compress=Y imp system/manager file=hr.dmp full=Y buffer=64000 commit=Y //备份表 exp system/manager FILE=expdat.dmp TABLES=(Thumper.SALES) //备份分区 exp system/manager FILE=expdat.dmp TABLES=(Thumper.SALES:Part1) //输入例子 imp system/manager file=expdat.dmp imp system/manager file=expdat.dmp buffer=64000 commit=Y exp system/manager file=thumper.dat owner=thumper grants=N indexes=Y compress=Y rows=Y imp system/manager file=thumper.dat FROMUSER=thumper TOUSER=flower rows=Y indexes=Y imp system/manager file=expdat.dmp full=Y commit=Y buffer=64000 imp system/manager file=expdat.dmp ignore=N rows=N commit=Y buffer=64000 //使用操作系统备份命令 REM TAR examples tar -cvf /dev/rmt/0hc /db0[1-9]/oracle/CC1 tar -rvf /dev/rmt/0hc /orasw/app/oracle/CC1/pfile/initcc1.ora tar -rvf /dev/rmt/0hc /db0[1-9]/oracle/CC1 /orasw/app/oracle/CC1/pfile/initcc1.ora //离线备份的shell脚本 ORACLE_SID=cc1; export ORACLE_SID ORAENV_ASK=NO; export ORAENV_ASK . oraenv svrmgrl <<EOF1 connect internal as sysdba shutdown immediate; exit EOF1 insert backup commands like the "tar" commands here svrmgrl <<EOF2 connect internal as sysdba startup EOF2 //在Server Manager上设置为archivelog mode: connect internal as sysdba startup mount cc1; alter database archivelog; archive log start; alter database open; //在Server Manager上设置为archivelog mode: connect internal as sysdba startup mount cc1; alter database noarchivelog; alter database open; select Name, Value from V$PARAMETER where Name like ’log_archive%’; //联机备份的脚本 # # Sample Hot Backup Script for a UNIX File System database # # Set up environment variables: ORACLE_SID=cc1; export ORACLE_SID ORAENV_ASK=NO; export ORAENV_ASK . oraenv svrmgrl <<EOFarch1 connect internal as sysdba REM REM 备份 SYSTEM tablespace REM alter tablespace SYSTEM begin backup; !tar -cvf /dev/rmt/0hc /db01/oracle/CC1/sys01.dbf alter tablespace SYSTEM end backup; REM REM The SYSTEM tablespace has now been written to a REM tar saveset on the tape device /dev/rmt/0hc. The REM rest of the tars must use the "-rvf" clause to append REM to that saveset. REM REM 备份 RBS tablespace REM alter tablespace RBS begin backup; !tar -rvf /dev/rmt/0hc /db02/oracle/CC1/rbs01.dbf alter tablespace RBS end backup; REM REM 备份 DATA tablespace REM For the purposes of this example, this tablespace REM will contain two files, data01.dbf and data02.dbf. REM The * wildcard will be used in the filename. REM alter tablespace DATA begin backup; !tar -rvf /dev/rmt/0hc /db03/oracle/CC1/data0*.dbf alter tablespace DATA end backup; REM REM 备份 INDEXES tablespace REM alter tablespace INDEXES begin backup; !tar -rvf /dev/rmt/0hc /db04/oracle/CC1/indexes01.dbf alter tablespace INDEXES end backup; REM REM 备份 TEMP tablespace REM alter tablespace TEMP begin backup; !tar -rvf /dev/rmt/0hc /db05/oracle/CC1/temp01.dbf alter tablespace TEMP end backup; REM REM Follow the same pattern to back up the rest REM of the tablespaces. REM REM REM Step 2. 备份归档日志文件. archive log stop REM REM Exit Server Manager, using the indicator set earlier. exit EOFarch1 # # Record which files are in the destination directory. # Do this by setting an environment variable that is # equal to the directory listing for the destination # directory. # For this example, the log_archive_dest is # /db01/oracle/arch/CC1. # FILES=`ls /db01/oracle/arch/CC1/arch*.dbf`; export FILES # # Now go back into Server Manager and restart the # archiving process. Set an indicator (called EOFarch2 # in this example). # svrmgrl <<EOFarch2 connect internal archive log start; exit EOFarch2 # # Now back up the archived redo logs to the tape # device via the "tar" command, then delete them # from the destination device via the "rm" command. # You may choose to compress them instead. # tar -rvf /dev/rmt/0hc $FILES rm -f $FILES # # Step 3. 备份控制文件到磁盘. # svrmgrl <<EOFarch3 connect internal alter database backup controlfile to ’db01/oracle/CC1/CC1controlfile.bck’; exit EOFarch3 # # 备份控制文件到磁带. # tar -rvf /dev/rmt/0hc /db01/oracle/CC1/CC1controlfile.bck # # End of hot backup script. //自动生成开始备份的脚本 set pagesize 0 feedback off select ’alter tablespace ’||Tablespace_Name||’ begin backup;’ from DBA_TABLESPACES where Status ’INVALID’ spool alter_begin.sql / spool off //自动生成备份结束的脚本 set pagesize 0 feedback off select ’alter tablespace ’||Tablespace_Name||’ end backup;’ from DBA_TABLESPACES where Status ’INVALID’ spool alter_end.sql / spool off //备份归档日志文件的脚本. REM See text for alternatives. # Step 1: Stop the archiving process. This will keep # additional archived redo log files from being written # to the destination directory during this process. # svrmgrl <<EOFarch1 connect internal as sysdba archive log stop; REM REM Exit Server Manager using the indicator set earlier. exit EOFarch1 # # Step 2: Record which files are in the destination # directory. # Do this by setting an environment variable that is # equal to the directory listing for the destination # directory. # For this example, the log_archive_dest is # /db01/oracle/arch/CC1. # FILES=`ls /db01/oracle/arch/CC1/arch*.dbf`; export FILES # # Step 3: Go back into Server Manager and restart the # archiving process. Set an indicator (called EOFarch2 # in this example). # svrmgrl <<EOFarch2 connect internal as sysdba archive log start; exit EOFarch2 # # Step 4. Back up the archived redo logs to the tape # device via the "tar" command, then delete them # from the destination device via the "rm" command. # tar -rvf /dev/rmt/0hc $FILES # # Step 5. Delete those files from the destination directory. # rm -f $FILES # # End of archived redo log file backup script. REM 磁盘到磁盘的备份 REM REM Back up the RBS tablespace - to another disk (UNIX) REM alter tablespace RBS begin backup; !cp /db02/oracle/CC1/rbs01.dbf /db10/oracle/CC1/backups alter tablespace RBS end backup; REM REM 移动归档日志文件的shell脚本 # # Procedure for moving archived redo logs to another device # svrmgrl <<EOFarch2 connect internal as sysdba archive log stop; !mv /db01/oracle/arch/CC1 /db10/oracle/arch/CC1 archive log start; exit EOFarch2 # # end of archived redo log directory move. //生成创建控制文件命令 alter database backup controlfile to trace; //时间点恢复的例子 connect internal as sysdba startup mount instance_name; recover database until time ’1999-08-07:14:40:00’; //创建恢复目录 rman rcvcat rman/rman@ // 在(UNIX)下创建恢复目录 RMAN> create catalog tablespace rcvcat; // 在(NT)下创建恢复目录 RMAN> create catalog tablespace "RCVCAT"; //连接描述符范例 (DESCRIPTION= (ADDRESS= (PROTOCOL=TCP) (HOST=HQ) (PORT=1521)) (CONNECT DATA= (SID=loc))) // listener.ora 的条目entry //创建一个控制文件命令到跟踪文件 alter database backup controlfile to trace; //增加一个新的日志文件组的语句 connect internal as sysdba alter database add logfile group 4 (’/db01/oracle/CC1/log_1c.dbf’, ’/db02/oracle/CC1/log_2c.dbf’) size 5M; alter database add logfile member ’/db03/oracle/CC1/log_3c.dbf’ to group 4; //在Server Manager上MOUNT并打开一个数据库: connect internal as sysdba startup mount ORA1 exclusive; alter database open; //生成数据字典 @catalog @catproc //在init.ora 中备份数据库的位置 log_archive_dest_1 = ’/db00/arch’ log_archive_dest_state_1 = enable log_archive_dest_2 = "service=stby.world mandatory reopen=60" log_archive_dest_state_2 = enable //对用户的表空间的指定和管理相关的语句 create user USERNAME identified by PASSWORD default tablespace TABLESPACE_NAME; alter user USERNAME default tablespace TABLESPACE_NAME; alter user SYSTEM quota 0 on SYSTEM; alter user SYSTEM quota 50M on TOOLS; create user USERNAME identified by PASSWORD default tablespace DATA temporary tablespace TEMP; alter user USERNAME temporary tablespace TEMP; //重新指定一个数据文件的大小 : alter database datafile ’/db05/oracle/CC1/data01.dbf’ resize 200M; //创建一个自动扩展的数据文件: create tablespace DATA datafile ’/db05/oracle/CC1/data01.dbf’ size 200M autoextend ON next 10M maxsize 250M; //在表空间上增加一个自动扩展的数据文件: alter tablespace DATA add datafile ’/db05/oracle/CC1/data02.dbf’ size 50M autoextend ON maxsize 300M; //修改参数: alter database datafile ’/db05/oracle/CC1/data01.dbf’ autoextend ON maxsize 300M; //在数据文件移动期间重新命名: alter database rename file ’/db01/oracle/CC1/data01.dbf’ to ’/db02/oracle/CC1/data01.dbf’; alter tablespace DATA rename datafile ’/db01/oracle/CC1/data01.dbf’ to ’/db02/oracle/CC1/data01.dbf’; alter database rename file ’/db05/oracle/CC1/redo01CC1.dbf’ to ’/db02/oracle/CC1/redo01CC1.dbf’; alter database datafile ’/db05/oracle/CC1/data01.dbf’ resize 80M; //创建和使用角色: create role APPLICATION_USER; grant CREATE SESSION to APPLICATION_USER; grant APPLICATION_USER to username; //回滚段的管理 create rollback segment SEGMENT_NAME tablespace RBS; alter rollback segment SEGMENT_NAME offline; drop rollback segment SEGMENT_NAME; alter rollback segment SEGMENT_NAME online; //回滚段上指定事务 commit; set transaction use rollback segment ROLL_BATCH; insert into TABLE_NAME select * from DATA_LOAD_TABLE; commit; //查询回滚段的 大小和优化参数 select * from DBA_SEGMENTS where Segment_Type = ’ROLLBACK’; select N.Name, /* rollback segment name */ S.OptSize /* rollback segment OPTIMAL size */ from V$ROLLNAME N, V$ROLLSTAT S where N.USN=S.USN; //回收回滚段 alter rollback segment R1 shrink to 15M; alter rollback segment R1 shrink; //例子 set transaction use rollback segment SEGMENT_NAME alter tablespace RBS default storage (initial 125K next 125K minextents 18 maxextents 249) create rollback segment R4 tablespace RBS storage (optimal 2250K); alter rollback segment R4 online; select Sessions_Highwater from V$LICENSE; grant select on EMPLOYEE to PUBLIC; //用户和角色 create role ACCOUNT_CREATOR; grant CREATE SESSION, CREATE USER, ALTER USER to ACCOUNT_CREATOR; alter user THUMPER default role NONE; alter user THUMPER default role CONNECT; alter user THUMPER default role all except ACCOUNT_CREATOR; alter profile DEFAULT limit idle_time 60; create profile LIMITED_PROFILE limit FAILED_LOGIN_ATTEMPTS 5; create user JANE identified by EYRE profile LIMITED_PROFILE; grant CREATE SESSION to JANE; alter user JANE account unlock; alter user JANE account lock; alter profile LIMITED_PROFILE limit PASSWORD_LIFE_TIME 30; alter user jane password expire; //创建操作系统用户 REM Creating OPS$ accounts create user OPS$FARMER identified by SOME_PASSWORD default tablespace USERS temporary tablespace TEMP; REM Using identified externally create user OPS$FARMER identified externally default tablespace USERS temporary tablespace TEMP; //执行ORAPWD ORAPWD FILE=filename PASSWORD=password ENTRIES=max_users create role APPLICATION_USER; grant CREATE SESSION to APPLICATION_USER; create role DATA_ENTRY_CLERK; grant select, insert on THUMPER.EMPLOYEE to DATA_ENTRY_CLERK; grant select, insert on THUMPER.TIME_CARDS to DATA_ENTRY_CLERK; grant select, insert on THUMPER.DEPARTMENT to DATA_ENTRY_CLERK; grant APPLICATION_USER to DATA_ENTRY_CLERK; grant DATA_ENTRY_CLERK to MCGREGOR; grant DATA_ENTRY_CLERK to BPOTTER with admin option; //设置角色 set role DATA_ENTRY_CLERK; set role NONE; //回收权利: revoke delete on EMPLOYEE from PETER; revoke all on EMPLOYEE from MCGREGOR; //回收角色: revoke ACCOUNT_CREATOR from HELPDESK; drop user USERNAME cascade; grant SELECT on EMPLOYEE to MCGREGOR with grant option; grant SELECT on THUMPER.EMPLOYEE to BPOTTER with grant option; revoke SELECT on EMPLOYEE from MCGREGOR; create user MCGREGOR identified by VALUES ’1A2DD3CCEE354DFA’; alter user OPS$FARMER identified by VALUES ’no way’; //备份与恢复 使用 export 程序 exp system/manager file=expdat.dmp compress=Y owner=(HR,THUMPER) exp system/manager file=hr.dmp owner=HR indexes=Y compress=Y imp system/manager file=hr.dmp full=Y buffer=64000 commit=Y //备份表 exp system/manager FILE=expdat.dmp TABLES=(Thumper.SALES) //备份分区 exp system/manager FILE=expdat.dmp TABLES=(Thumper.SALES:Part1) //输入例子 imp system/manager file=expdat.dmp imp system/manager file=expdat.dmp buffer=64000 commit=Y exp system/manager file=thumper.dat owner=thumper grants=N indexes=Y compress=Y rows=Y imp system/manager file=thumper.dat FROMUSER=thumper TOUSER=flower rows=Y indexes=Y imp system/manager file=expdat.dmp full=Y commit=Y buffer=64000 imp system/manager file=expdat.dmp ignore=N rows=N commit=Y buffer=64000 //使用操作系统备份命令 REM TAR examples tar -cvf /dev/rmt/0hc /db0[1-9]/oracle/CC1 tar -rvf /dev/rmt/0hc /orasw/app/oracle/CC1/pfile/initcc1.ora tar -rvf /dev/rmt/0hc /db0[1-9]/oracle/CC1 /orasw/app/oracle/CC1/pfile/initcc1.ora //离线备份的shell脚本 ORACLE_SID=cc1; export ORACLE_SID ORAENV_ASK=NO; export ORAENV_ASK . oraenv svrmgrl <<EOF1 connect internal as sysdba shutdown immediate; exit EOF1 insert backup commands like the "tar" commands here svrmgrl <<EOF2 connect internal as sysdba startup EOF2 //在Server Manager上设置为archivelog mode: connect internal as sysdba startup mount cc1; alter database archivelog; archive log start; alter database open; //在Server Manager上设置为archivelog mode: connect internal as sysdba startup mount cc1; alter database noarchivelog; alter database open; select Name, Value from V$PARAMETER where Name like ’log_archive%’; //联机备份的脚本 # # Sample Hot Backup Script for a UNIX File System database # # Set up environment variables: ORACLE_SID=cc1; export ORACLE_SID ORAENV_ASK=NO; export ORAENV_ASK . oraenv svrmgrl <<EOFarch1 connect internal as sysdba REM REM 备份 SYSTEM tablespace REM alter tablespace SYSTEM begin backup; !tar -cvf /dev/rmt/0hc /db01/oracle/CC1/sys01.dbf alter tablespace SYSTEM end backup; REM REM The SYSTEM tablespace has now been written to a REM tar saveset on the tape device /dev/rmt/0hc. The REM rest of the tars must use the "-rvf" clause to append REM to that saveset. REM REM 备份 RBS tablespace REM alter tablespace RBS begin backup; !tar -rvf /dev/rmt/0hc /db02/oracle/CC1/rbs01.dbf alter tablespace RBS end backup; REM REM 备份 DATA tablespace REM For the purposes of this example, this tablespace REM will contain two files, data01.dbf and data02.dbf. REM The * wildcard will be used in the filename. REM alter tablespace DATA begin backup; !tar -rvf /dev/rmt/0hc /db03/oracle/CC1/data0*.dbf alter tablespace DATA end backup; REM REM 备份 INDEXES tablespace REM alter tablespace INDEXES begin backup; !tar -rvf /dev/rmt/0hc /db04/oracle/CC1/indexes01.dbf alter tablespace INDEXES end backup; REM REM 备份 TEMP tablespace REM alter tablespace TEMP begin backup; !tar -rvf /dev/rmt/0hc /db05/oracle/CC1/temp01.dbf alter tablespace TEMP end backup; REM REM Follow the same pattern to back up the rest REM of the tablespaces. REM REM REM Step 2. 备份归档日志文件. archive log stop REM REM Exit Server Manager, using the indicator set earlier. exit EOFarch1 # # Record which files are in the destination directory. # Do this by setting an environment variable that is # equal to the directory listing for the destination # directory. # For this example, the log_archive_dest is # /db01/oracle/arch/CC1. # FILES=`ls /db01/oracle/arch/CC1/arch*.dbf`; export FILES # # Now go back into Server Manager and restart the # archiving process. Set an indicator (called EOFarch2 # in this example). # svrmgrl <<EOFarch2 connect internal archive log start; exit EOFarch2 # # Now back up the archived redo logs to the tape # device via the "tar" command, then delete them # from the destination device via the "rm" command. # You may choose to compress them instead. # tar -rvf /dev/rmt/0hc $FILES rm -f $FILES # # Step 3. 备份控制文件到磁盘. # svrmgrl <<EOFarch3 connect internal alter database backup controlfile to ’db01/oracle/CC1/CC1controlfile.bck’; exit EOFarch3 # # 备份控制文件到磁带. # tar -rvf /dev/rmt/0hc /db01/oracle/CC1/CC1controlfile.bck # # End of hot backup script. //自动生成开始备份的脚本 set pagesize 0 feedback off select ’alter tablespace ’||Tablespace_Name||’ begin backup;’ from DBA_TABLESPACES where Status ’INVALID’ spool alter_begin.sql / spool off //自动生成备份结束的脚本 set pagesize 0 feedback off select ’alter tablespace ’||Tablespace_Name||’ end backup;’ from DBA_TABLESPACES where Status ’INVALID’ spool alter_end.sql / spool off //备份归档日志文件的脚本. REM See text for alternatives. # Step 1: Stop the archiving process. This will keep # additional archived redo log files from being written # to the destination directory during this process. # svrmgrl <<EOFarch1 connect internal as sysdba archive log stop; REM REM Exit Server Manager using the indicator set earlier. exit EOFarch1 # # Step 2: Record which files are in the destination # directory. # Do this by setting an environment variable that is # equal to the directory listing for the destination # directory. # For this example, the log_archive_dest is # /db01/oracle/arch/CC1. # FILES=`ls /db01/oracle/arch/CC1/arch*.dbf`; export FILES # # Step 3: Go back into Server Manager and restart the # archiving process. Set an indicator (called EOFarch2 # in this example). # svrmgrl <<EOFarch2 connect internal as sysdba archive log start; exit EOFarch2 # # Step 4. Back up the archived redo logs to the tape # device via the "tar" command, then delete them # from the destination device via the "rm" command. # tar -rvf /dev/rmt/0hc $FILES # # Step 5. Delete those files from the destination directory. # rm -f $FILES # # End of archived redo log file backup script. REM 磁盘到磁盘的备份 REM REM Back up the RBS tablespace - to another disk (UNIX) REM alter tablespace RBS begin backup; !cp /db02/oracle/CC1/rbs01.dbf /db10/oracle/CC1/backups alter tablespace RBS end backup; REM REM 移动归档日志文件的shell脚本 # # Procedure for moving archived redo logs to another device # svrmgrl <<EOFarch2 connect internal as sysdba archive log stop; !mv /db01/oracle/arch/CC1 /db10/oracle/arch/CC1 archive log start; exit EOFarch2 # # end of archived redo log directory move. //生成创建控制文件命令 alter database backup controlfile to trace; //时间点恢复的例子 connect internal as sysdba startup mount instance_name; recover database until time ’1999-08-07:14:40:00’; //创建恢复目录 rman rcvcat rman/rman@ // 在(UNIX)下创建恢复目录 RMAN> create catalog tablespace rcvcat; // 在(NT)下创建恢复目录 RMAN> create catalog tablespace "RCVCAT"; //连接描述符范例 (DESCRIPTION= (ADDRESS= (PROTOCOL=TCP) (HOST=HQ) (PORT=1521)) (CONNECT DATA= (SID=loc))) // listener.ora 的条目entry ……………………………………………………………………………………
一、约束:作用是保证数据的完整性和一致性 not null 表示该字段数据不能为空 default 表示该字段的默认值 unique 唯一(列唯一,组合唯一) primary key 主键 一张列表中只允许出现一个主键(not null + unique) auto-increment 自增长 foregin key 外键 建立两个表之间的联系 语法 constraint fk_dep foreign key(关联列名) references 被关联表(被关联列) on delete cascade 同步删除 on update cascade 同步更新 二、Mysql基本介绍 操作文件夹(库): 增加一个库:create database db1 charset utf8; 查看所有库: show databases; 查看特定库: show create database db1; 删库跑路: drop database db1; 操作文件(表): 切换进数据库:use db1; 查看当前所在文件夹;select database( ); 增加表:create table t1(id int,name char(6)); 查看特定表:show create table t1; 查看所有表:show tables;或者desc t1; 改: alter table t1 modify name char(10);name字段改为10字节; alter table t1 modify name NAME char(10);name字段名改成NAME 复制表 即复制表数据也复制表结构:create table t1 select * from db1.t1; 只复制表结构create table a1 like db1.t1; 清空表 delete from t1;但是这种方法会保留自增的ID truncate table t1;这种方法不会保留自增ID 操作文件内容 增加内容:insert into (id,name) values(1,'aa'),(2,'bb'),(3,'cc'); 查看内容:select * from db1.t1; 删除内容:delete from t1 where id =1; 查看用户权限:select * from mysql.user where user='root'\G; 三、SQL数据类型 SQL之中没有bool值,tinyint[1]表示true;tinyint[0]表示fasle. int数据类型后面存储的是显示宽度,而不是存储宽度,其他的数据类型则表示的是存储宽度 now()sql中的内置函数,根据数据类型生成相对应的时间模式 char( )定长字符串,存储速度快,但是浪费空间 varchar( )变长字符串,存储速度慢,可是节省空间 enum() 表示枚举 多选一 set( )表示集合 多选多 七、索引 索引的作用:约束和加速查找 无索引的时候一般会 从前至后一条条查找 有索引的时候:创建索引的本质就是创造额外的文件,查询时先去额外的文件找,定好位置,再去原始表直接查询,提高查询速度,但是增删改的速度依然慢,创建索引后必须命中索引才有效 索引的分类 1、普通索引:加速查询 加入索引:create index 索引名 on 表名(列名) 删除索引: drop index 索引名 on 表名 查看索引:show index from 表名 2、唯一索引:加速查找和唯一约束(可含null) 加入索引:create unique index 索引名 on 表名(列名) 删除:drop index 索引名 on 表名 3、主键索引 加入索引:alter table 表名 add primary key(列名) 删除索引:alter table 表名 drop primary key(列名)和alter table 表名 modify 列名 int,drop primary key 4、组合索引:将多个列组合成一个索引 创建组合索引:create iindex 索引名 on 表名(列1,列2) 在使用组合索引时,若组合索引为(name,email),单独索引email时不走索引,这称为最左前缀匹配原则,最左匹配原则中,mysql会一直向右匹配知道遇到(< > between like)这一类的范围查询时停止 explain + sql查询语句,用于查询sql执行信息参数 在使用关键字‘like’查询时:like ‘n%’ 走索引;但是like ‘%n%’不走索引,即有且仅只有后面带上%时走索引 使用函数时索引不生效

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值