码迷,mamicode.com
首页 > 数据库 > 详细

oracle常用经典SQL查询

时间:2017-08-29 20:42:37      阅读:246      评论:0      收藏:0      [点我收藏+]

标签:output   locate   proc   stat   outer   ret   arch   process   art   

 

  1 常用SQL查询:
  2 
  3 1、查看表空间的名称及大小
  4 
  5 select t.tablespace_name, round(sum(bytes/(1024*1024)),0) ts_size
  6 from dba_tablespaces t, dba_data_files d
  7 where t.tablespace_name = d.tablespace_name
  8 group by t.tablespace_name;
  9 
 10 2、查看表空间物理文件的名称及大小
 11 
 12 select tablespace_name, file_id, file_name,
 13 round(bytes/(1024*1024),0) total_space
 14 from dba_data_files
 15 order by tablespace_name;
 16 
 17 3、查看回滚段名称及大小
 18 
 19 select segment_name, tablespace_name, r.status,
 20 (initial_extent/1024) InitialExtent,(next_extent/1024) NextExtent,
 21 max_extents, v.curext CurExtent
 22 From dba_rollback_segs r, v$rollstat v
 23 Where r.segment_id = v.usn(+)
 24 order by segment_name;
 25 
 26 4、查看控制文件
 27 
 28 select name from v$controlfile;
 29 
 30 5、查看日志文件
 31 
 32 select member from v$logfile;
 33 
 34 6、查看表空间的使用情况
 35 
 36 select sum(bytes)/(1024*1024) as free_space,tablespace_name
 37 from dba_free_space
 38 group by tablespace_name;
 39 
 40 SELECT A.TABLESPACE_NAME,A.BYTES TOTAL,B.BYTES USED, C.BYTES FREE,
 41 (B.BYTES*100)/A.BYTES "% USED",(C.BYTES*100)/A.BYTES "% FREE"
 42 FROM SYS.***$TS_***AIL A,SYS.***$TS_USED B,SYS.***$TS_FREE C
 43 WHERE A.TABLESPACE_NAME=B.TABLESPACE_NAME AND A.TABLESPACE_NAME=C.TABLESPACE_NAME;
 44 
 45 7、查看数据库库对象
 46 
 47 select owner, object_type, status, count(*) count# from all_objects group by owner, object_type, status;
 48 
 49 8、查看数据库的版本
 50 
 51 Select version FROM Product_component_version
 52 Where SUBSTR(PRODUCT,1,6)=‘‘Oracle‘‘;
 53 
 54 9、查看数据库的创建日期和归档方式
 55 
 56 Select Created, Log_Mode, Log_Mode From V$Database;
 57 
 58 10、捕捉运行很久的SQL
 59 
 60 column username format a12
 61 column opname format a16
 62 column progress format a8
 63 
 64 select username,sid,opname,
 65       round(sofar*100 / totalwork,0) || ‘‘%‘as progress,
 66       time_remaining,sql_text
 67 from v$session_longops , v$sql
 68 where time_remaining <> 0
 69 and sql_address = address
 70 and sql_hash_value = hash_value
 71 /
 72 11。查看数据表的参数信息
 73 SELECT   partition_name, high_value, high_value_length, tablespace_name,
 74         pct_free, pct_used, ini_trans, max_trans, initial_extent,
 75         next_extent, min_extent, max_extent, pct_increase, FREELISTS,
 76         freelist_groups, LOGGING, BUFFER_POOL, num_rows, blocks,
 77         empty_blocks, ***g_space, chain_cnt, ***g_row_len, sample_size,
 78         last_analyzed
 79    FROM dba_tab_partitions
 80   --WHERE table_name = :tname AND table_owner = :towner
 81 ORDER BY partition_position
 82 
 83 12.查看还没提交的事务
 84 select * from v$locked_object;
 85 select * from v$transaction;
 86 
 87 13。查找object为哪些进程所用
 88 select
 89 p.spid,
 90 s.sid,
 91 s.serial# serial_num,
 92 s.username user_name,
 93 a.type  object_type,
 94 s.osuser os_user_name,
 95 a.owner,
 96 a.object object_name,
 97 decode(sign(48 - command),
 98 1,
 99 to_char(command), ‘‘Action Code #‘‘ || to_char(command) ) action,
100 p.program oracle_process,
101 s.terminal terminal,
102 s.program program,
103 s.status session_status
104 from v$session s, v$access a, v$process p
105 where s.paddr = p.addr and
106      s.type = ‘‘USER‘‘ and
107      a.sid = s.sid   and
108   a.object=‘‘SUBSCRIBER_ATTR‘109 order by s.username, s.osuser
110 
111 14。回滚段查看
112 select rownum, sys.dba_rollback_segs.segment_name Name, v$rollstat.extents
113 Extents, v$rollstat.rssize Size_in_Bytes, v$rollstat.xacts XActs,
114 v$rollstat.gets Gets, v$rollstat.waits Waits, v$rollstat.writes Writes,
115 sys.dba_rollback_segs.status status from v$rollstat, sys.dba_rollback_segs,
116 v$rollname where v$rollname.name(+) = sys.dba_rollback_segs.segment_name and
117 v$rollstat.usn (+) = v$rollname.usn order by rownum
118 
119 15。耗资源的进程(top session120 select s.schemaname schema_name,    decode(sign(48 - command), 1,
121 to_char(command), ‘‘Action Code #‘‘ || to_char(command) ) action,    status
122 session_status,   s.osuser os_user_name,   s.sid,         p.spid ,         s.serial# serial_num,
123 nvl(s.username, ‘‘[Oracle process]‘‘) user_name,   s.terminal terminal,
124 s.program program,   st.value criteria_value  from v$sesstat st,   v$session s  , v$process p
125 where st.sid = s.sid and   st.statistic# = to_number(‘‘38‘‘) and   (‘‘ALL‘‘ = ‘‘ALL‘126 or s.status = ‘‘ALL‘‘) and p.addr = s.paddr order by st.value desc,  p.spid asc, s.username asc, s.osuser asc
127 
128 16。查看锁(lock)情况
129 select /*+ RULE */ ls.osuser os_user_name,   ls.username user_name,
130 decode(ls.type, ‘‘RW‘‘, ‘‘Row wait enqueue lock‘‘, ‘‘TM‘‘, ‘‘DML enqueue lock‘‘, ‘‘TX‘‘,
131‘Transaction enqueue lock‘‘, ‘‘UL‘‘, ‘‘User supplied lock‘‘) lock_type,
132 o.object_name object,   decode(ls.lmode, 1, null, 2, ‘‘Row Share‘‘, 3,
133‘Row Exclusive‘‘, 4, ‘‘Share‘‘, 5, ‘‘Share Row Exclusive‘‘, 6, ‘‘Exclusive‘‘, null)
134 lock_mode,    o.owner,   ls.sid,   ls.serial# serial_num,   ls.id1,   ls.id2
135 from sys.dba_objects o, (   select s.osuser,    s.username,    l.type,
136 l.lmode,    s.sid,    s.serial#,    l.id1,    l.id2   from v$session s,
137 v$lock l   where s.sid = l.sid ) ls  where o.object_id = ls.id1 and    o.owner
138 <> ‘‘SYS‘order by o.owner, o.object_name
139 
140 17。查看等待(wait)情况
141 SELECT v$waitstat.class, v$waitstat.count count, SUM(v$sysstat.value) sum_value
142 FROM v$waitstat, v$sysstat WHERE v$sysstat.name IN (‘‘db block gets‘‘,
143‘consistent gets‘‘) group by v$waitstat.class, v$waitstat.count
144 
145 18。查看sga情况
146 SELECT NAME, BYTES FROM SYS.V_$SGASTAT ORDER BY NAME ASC
147 
148 19。查看catched object
149 SELECT owner,              name,              db_link,              namespace,
150            type,              sharable_mem,              loads,              executions,
151           locks,              pins,              kept        FROM v$db_object_cache
152 
153 20。查看V$SQLAREA
154 SELECT SQL_TEXT, SHARABLE_MEM, PERSISTENT_MEM, RUNTIME_MEM, SORTS,
155 VERSION_COUNT, LOADED_VERSIONS, OPEN_VERSIONS, USERS_OPENING, EXECUTIONS,
156 USERS_EXECUTING, LOADS, FIRST_LOAD_TIME, INVALIDATIONS, PARSE_CALLS, DISK_READS,
157 BUFFER_GETS, ROWS_PROCESSED FROM V$SQLAREA
158 
159 21。查看object分类数量
160 select decode (o.type#,1,‘‘INDEX‘‘ , 2,‘‘TABLE‘‘ , 3 , ‘‘CLUSTER‘‘ , 4, ‘‘VIEW‘‘ , 5 ,
161‘SYNONYM‘‘ , 6 , ‘‘SEQUENCE‘‘ , ‘‘OTHER‘‘ ) object_type , count(*) quantity from
162 sys.obj$ o where o.type# > 1 group by decode (o.type#,1,‘‘INDEX‘‘ , 2,‘‘TABLE‘‘ , 3
163 , ‘‘CLUSTER‘‘ , 4, ‘‘VIEW‘‘ , 5 , ‘‘SYNONYM‘‘ , 6 , ‘‘SEQUENCE‘‘ , ‘‘OTHER‘‘ ) union select
164‘COLUMN‘‘ , count(*) from sys.col$ union select‘DB LINK‘‘ , count(*) from
165 
166 22。按用户查看object种类
167 select u.name schema,   sum(decode(o.type#, 1, 1, NULL)) indexes,
168 sum(decode(o.type#, 2, 1, NULL)) tables,   sum(decode(o.type#, 3, 1, NULL))
169 clusters,   sum(decode(o.type#, 4, 1, NULL)) views,   sum(decode(o.type#, 5, 1,
170 NULL)) synonyms,   sum(decode(o.type#, 6, 1, NULL)) sequences,
171 sum(decode(o.type#, 1, NULL, 2, NULL, 3, NULL, 4, NULL, 5, NULL, 6, NULL, 1))
172 others   from sys.obj$ o, sys.user$ u   where o.type# >= 1 and    u.user# =
173 o.owner# and   u.name <> ‘‘PUBLIC‘group by u.name    order by
174 sys.link$ union select‘CONSTRAINT‘‘ , count(*) from sys.con$
175 
176 23。有关connection的相关信息
177 1)查看有哪些用户连接
178 select s.osuser os_user_name,    decode(sign(48 - command), 1, to_char(command),
179‘Action Code #‘‘ || to_char(command) ) action,     p.program oracle_process,
180 status session_status,    s.terminal terminal,    s.program program,
181 s.username user_name,    s.fixed_table_sequence activity_meter,    ‘‘‘‘ query,
182 0 memory,    0 max_memory,     0 cpu_usage,    s.sid,   s.serial# serial_num
183 from v$session s,    v$process p   where s.paddr=p.addr and    s.type = ‘‘USER‘184 order by s.username, s.osuser
185 2)根据v.sid查看对应连接的资源占用等情况
186 select n.name,
187  v.value,
188  n.class,
189  n.statistic#
190 from  v$statname n,
191  v$sesstat v
192 where v.sid = 71 and
193  v.statistic# = n.statistic#
194 order by n.class, n.statistic#
195 3)根据sid查看对应连接正在运行的sql
196 select /*+ PUSH_SUBQ */
197  command_type,
198  sql_text,
199  sharable_mem,
200  persistent_mem,
201  runtime_mem,
202  sorts,
203  version_count,
204  loaded_versions,
205  open_versions,
206  users_opening,
207  executions,
208  users_executing,
209  loads,
210  first_load_time,
211  invalidations,
212  parse_calls,
213  disk_reads,
214  buffer_gets,
215  rows_processed,
216  sysdate start_time,
217  sysdate finish_time,
218‘>‘‘ || address sql_address,
219‘N‘‘ status
220 from v$sqlarea
221 where address = (select sql_address from v$session where sid = 71)
222 
223 24.查询表空间使用情况
224 select a.tablespace_name "表空间名称",
225 100-round((nvl(b.bytes_free,0)/a.bytes_alloc)*100,2) "占用率(%)",
226 round(a.bytes_alloc/1024/1024,2) "容量(M)",
227 round(nvl(b.bytes_free,0)/1024/1024,2) "空闲(M)",
228 round((a.bytes_alloc-nvl(b.bytes_free,0))/1024/1024,2) "使用(M)",
229 Largest "最大扩展段(M)",
230 to_char(sysdate,‘‘yyyy-mm-dd hh24:mi:ss‘‘) "采样时间"
231 from  (select f.tablespace_name,
232    sum(f.bytes) bytes_alloc,
233    sum(decode(f.autoextensible,‘‘YES‘‘,f.maxbytes,‘‘NO‘‘,f.bytes)) maxbytes
234 from dba_data_files f
235 group by tablespace_name) a,
236 (select  f.tablespace_name,
237     sum(f.bytes) bytes_free
238 from dba_free_space f
239 group by tablespace_name) b,
240 (select round(max(ff.length)*16/1024,2) Largest,
241    ts.name tablespace_name
242 from sys.fet$ ff, sys.file$ tf,sys.ts$ ts
243 where ts.ts#=ff.ts# and ff.file#=tf.relfile# and ts.ts#=tf.ts#
244 group by ts.name, tf.blocks) c
245 where a.tablespace_name = b.tablespace_name and a.tablespace_name = c.tablespace_name
246 
247 25. 查询表空间的碎片程度
248 
249 select tablespace_name,count(tablespace_name) from dba_free_space group by tablespace_name
250 h***ing count(tablespace_name)>10;
251 
252 alter tablespace name coalesce;
253 alter table name deallocate unused;
254 
255 create or replace view ts_blocks_v as
256 select tablespace_name,block_id,bytes,blocks,‘‘free space‘ segment_name from dba_free_space
257 union all
258 select tablespace_name,block_id,bytes,blocks,segment_name from dba_extents;
259 
260 select * from ts_blocks_v;
261 
262 select tablespace_name,sum(bytes),max(bytes),count(block_id) from dba_free_space
263 group by tablespace_name;
264 
265 26。查询有哪些数据库实例在运行
266 select inst_name from v$active_instances;
267 
268 ===========================================================
269 ######### 创建数据库----look $ORACLE_HOME/rdbms/admin/buildall.sql ############# 
270 
271 create database db01
272 maxlogfiles 10
273 maxdatafiles 1024
274 maxinstances 2
275 logfile
276 GROUP 1 (‘‘/u01/oradata/db01/log_01_db01.rdo‘‘) SIZE 15M,
277 GROUP 2 (‘‘/u01/oradata/db01/log_02_db01.rdo‘‘) SIZE 15M,
278 GROUP 3 (‘‘/u01/oradata/db01/log_03_db01.rdo‘‘) SIZE 15M,
279 datafile ‘‘u01/oradata/db01/system_01_db01.dbf‘‘) SIZE 100M,
280 undo tablespace UNDO
281 datafile ‘‘/u01/oradata/db01/undo_01_db01.dbf‘‘ SIZE 40M
282 default temporary tablespace TEMP
283 tempfile ‘‘/u01/oradata/db01/temp_01_db01.dbf‘‘ SIZE 20M
284 extent management local uniform size 128k
285 character set AL32UTE8
286 national character set AL16UTF16
287 set time_zone=‘‘America/New_York‘‘;
288 
289 ############### 数据字典 ##########
290 
291 set wrap off
292 
293 select * from v$dba_users;
294 
295 grant select on table_name to user/rule;
296 
297 select * from user_tables;
298 
299 select * from all_tables;
300 
301 select * from dba_tables;
302 
303 revoke dba from user_name;
304 
305 shutdown immediate
306 
307 startup nomount
308 
309 select * from v$instance;
310 
311 select * from v$sga;
312 
313 select * from v$tablespace;
314 
315 alter session set nls_language=american;
316 
317 alter database mount;
318 
319 select * from v$database;
320 
321 alter database open;
322 
323 desc dictionary
324 
325 select * from dict;
326 
327 desc v$fixed_table;
328 
329 select * from v$fixed_table;
330 
331 set oracle_sid=foxconn
332 
333 select * from dba_objects;
334 
335 set serveroutput on
336 
337 execute dbms_output.put_line(‘‘sfasd‘‘);
338 
339 ############# 控制文件 ###########
340 
341 select * from v$database;
342 
343 select * from v$tablespace;
344 
345 select * from v$logfile;
346 
347 select * from v$log;
348 
349 select * from v$backup;
350 
351 /*备份用户表空间*/
352 alter tablespace users begin backup;
353 
354 select * from v$archived_log;
355 
356 select * from v$controlfile;
357 
358 alter system set control_files=‘‘$ORACLE_HOME/oradata/u01/ctrl01.ctl‘‘,
359‘$ORACLE_HOME/oradata/u01/ctrl02.ctl‘‘ scope=spfile;
360 
361 cp $ORACLE_HOME/oradata/u01/ctrl01.ctl $ORACLE_HOME/oradata/u01/ctrl02.ctl
362 
363 startup pfile=‘‘../initSID.ora‘364 
365 select * from v$parameter where name like‘control%‘‘ ;
366 
367 show parameter control;
368 
369 select * from v$controlfile_record_section;
370 
371 select * from v$tempfile;
372 
373 /*备份控制文件*/
374 alter database backup controlfile to‘../filepath/control.bak‘‘;
375 
376 /*备份控制文件,并将二进制控制文件变为了asc 的文本文件*/
377 alter database backup controlfile to trace;
378 
379 ############### redo log ##############
380 
381 archive log list;
382 
383 alter system archive log start;--启动自动存档 
384 
385 alter system switch logfile;--强行进行一次日志switch 
386 
387 alter system checkpoint;--强制进行一次checkpoint 
388 
389 alter tablspace users begin backup;
390 
391 alter tablespace offline;
392 
393 /*checkpoint 同步频率参数FAST_START_MTTR_TARGET,同步频率越高,系统恢复所需时间越短*/
394 show parameter fast;
395 
396 show parameter log_checkpoint;
397 
398 /*加入一个日志组*/
399 alter database add logfile group 3 (‘‘/$ORACLE_HOME/oracle/ora_log_file6.rdo‘‘ size 10M);
400 
401 /*加入日志组的一个成员*/
402 alter database add logfile member ‘‘/$ORACLE_HOME/oracle/ora_log_file6.rdo‘‘ to group 3;
403 
404 /*删除日志组:当前日志组不能删;活动的日志组不能删;非归档的日志组不能删*/
405 alter database drop logfile group 3;
406 
407 /*删除日志组中的某个成员,但每个组的最后一个成员不能被删除*/
408 alter databse drop logfile member ‘‘$ORACLE_HOME/oracle/ora_log_file6.rdo‘‘;
409 
410 /*清除在线日志*/
411 alter database clear logfile ‘‘$ORACLE_HOME/oracle/ora_log_file6.rdo‘‘;
412 
413 alter database clear logfile group 3;
414 
415 /*清除非归档日志*/
416 alter database clear unarchived logfile group 3;
417 
418 /*重命名日志文件*/
419 alter database rename file‘$ORACLE_HOME/oracle/ora_log_file6.rdo‘‘ to ‘‘$ORACLE_HOME/oracle/ora_log_file6a.rdo‘‘;
420 
421 show parameter db_create;
422 
423 alter system set db_create_online_log_dest_1=‘‘path_name‘‘;
424 
425 select * from v$log;
426 
427 select * from v$logfile;
428 
429 /*数据库归档模式到非归档模式的互换,要启动到mount状态下才能改变;startup mount;然后再打开数据库.*/
430 alter database noarchivelog/archivelog;
431 
432 achive log start;---启动自动归档 
433 
434 alter system archive all;--手工归档所有日志文件
435 
436 select * from v$archived_log;
437 
438 show parameter log_archive;
439 
440 ###### 分析日志文件logmnr ##############
441 
442 1) 在init.ora中set utl_file_dir 参数
443 2) 重新启动oracle
444 3) create 目录文件
445 desc dbms_logmnr_d;
446 dbms_logmnr_d.build;
447 4) 加入日志文件 add/remove log file
448 dhms_logmnr.add_logfile
449 dbms_logmnr.removefile
450 5) start logmnr
451 dbms_logmnr.start_logmnr
452 6) 分析出来的内容查询 v$logmnr_content --sqlredo/sqlundo 
453 
454 实践:
455 
456 desc dbms_logmnr_d;
457 
458 /*对数据表做一些操作,为恢复操作做准备*/
459 updateset qty=10 where stor_id=6380;
460 
461 deletewhere stor_id=7066;
462 /***********************************/
463 utl_file_dir的路径
464 execute dbms_logmnr_d.build(‘‘foxdict.ora‘‘,‘‘$ORACLE_HOME/oracle/admin/fox/cdump‘‘);
465 
466 execute dbms_logmnr.add_logfile(‘‘$ORACLE_HOME/oracle/ora_log_file6.log‘‘,dbms_logmnr.newfile);
467 
468 execute dbms_logmnr.start_logmnr(dictfilename=>‘‘$ORACLE_HOME/oracle/admin/fox/cdump/foxdict.ora‘‘);
469 
470 ######### tablespace ##############
471 
472 select * form v$tablespace;
473 
474 select * from v$datafile;
475 
476 /*表空间和数据文件的对应关系*/
477 select t1.name,t2.name from v$tablespace t1,v$datafile t2 where t1.ts#=t2.ts#;
478 
479 alter tablespace users add datafile ‘‘path‘‘ size 10M;
480 
481 select * from dba_rollback_segs;
482 
483 /*限制用户在某表空间的使用限额*/
484 alter user user_name quota 10m on tablespace_name;
485 
486 create tablespace xxx [datafile ‘‘path_name/datafile_name‘‘] [size xxx] [extent management local/dictionary] [default storage(xxx)];
487 
488 exmple: create tablespace userdata datafile ‘‘$ORACLE_HOME/oradata/userdata01.dbf‘‘ size 100M AUTOEXTEND ON NEXT 5M MAXSIZE 200M;
489 create tablespace userdata datafile ‘‘$ORACLE_HOME/oradata/userdata01.dbf‘‘ size 100M extent management dictionary default storage(initial 100k next 100k pctincrease 10) offline;
490 /*9i以后,oracle建议使用local管理,而不使用dictionary管理,因为local采用bitmap管理表空间 ,不会产生系统表空间的自愿争用;*/
491 create tablespace userdata datafile ‘‘$ORACLE_HOME/oradata/userdata01.dbf‘‘ size 100M extent management local uniform size 1m;
492 create tablespace userdata datafile ‘‘$ORACLE_HOME/oradata/userdata01.dbf‘‘ size 100M extent management local autoallocate;
493 /*在创建表空间时,设置表空间内的段空间管理模式,这里用的是自动管理*/
494 create tablespace userdata datafile ‘‘$ORACLE_HOME/oradata/userdata01.dbf‘‘ size 100M extent management local uniform size 1m segment space management auto;
495 
496 alter tablespace userdata mininum extent 10;
497 
498 alter tablespace userdata default storage(initial 1m next 1m pctincrease 20);
499 
500 /*undo tablespace(不能被用在字典管理模下) */
501 create undo tablespace undo1 datafile ‘‘$ORACLE_HOME/oradata/undo101.dbf‘‘ size 40M extent management local;
502 
503 show parameter undo;
504 
505 /*temporary tablespace*/
506 create temporary tablespace userdata tempfile ‘‘$ORACLE_HOME/oradata/undo101.dbf‘‘ size 10m extent management local;
507 
508 /*设置数据库缺省的临时表空间*/
509 alter database default temporary tablespace tablespace_name;
510 
511 /*系统/临时/在线的undo表空间不能被offline*/
512 alter tablespace tablespace_name offline/online;
513 
514 alter tablespace tablespace_name read only;
515 
516 /*重命名用户表空间*/
517 alter tablespace tablespace_name rename datafile ‘‘$ORACLE_HOME/oradata/undo101.dbf‘‘ to ‘‘$ORACLE_HOME/oradata/undo102.dbf‘‘;
518 
519 /*重命名系统表空间 ,但在重命名前必须将数据库shutdown,并重启到mount状态*/
520 alter database rename file‘$ORACLE_HOME/oradata/system01.dbf‘‘ to ‘‘$ORACLE_HOME/oradata/system02.dbf‘‘;
521 
522 drop tablespace userdata including contents and datafiles;---drop tablespce 
523 
524 /*resize tablespace,autoextend datafile space*/
525 alter database datafile ‘‘$ORACLE_HOME/oradata/undo102.dbf‘‘ autoextend on next 10m maxsize 500M;
526 
527 /*resize datafile*/
528 alter database datafile ‘‘$ORACLE_HOME/oradata/undo102.dbf‘‘ resize 50m;
529 
530 /*给表空间扩展空间*/
531 alter tablespace userdata add datafile ‘‘$ORACLE_HOME/oradata/undo102.dbf‘‘ size 10m;
532 
533 /*将表空间设置成OMF状态*/
534 alter system set db_create_file_dest=‘‘$ORACLE_HOME/oradata‘‘;
535 
536 create tablespace userdata;---use OMF status to create tablespace; 
537 
538 drop tablespace userdata;---user OMF status to drop tablespace; 
539 
540 select * from dba_tablespace/v$tablespace/dba_data_files;
541 
542 /*将表的某分区移动到另一个表空间*/
543 alter table table_name move partition partition_name tablespace tablespace_name;
544 
545 ###### ORACLE storage structure and relationships #########
546 
547 /*手工分配表空间段的分区(extend)大小*/
548 alter table kong.test12 allocate extent(size 1m datafile ‘‘$ORACLE_HOME/oradata/undo102.dbf‘‘);
549 
550 alter table kong.test12 deallocate unused; ---释放表中没有用到的分区 
551 
552 show parameter db;
553 
554 alter system set db_8k_cache_size=10m; ---配置8k块的内存空间块参数 
555 
556 select * from dba_extents/dba_segments/data_tablespace;
557 
558 select * from dba_free_space/dba_data_file/data_tablespace;
559 
560 /*数据对象所占用的字节数*/
561 select sum(bytes) from dba_extents where onwer=‘‘kong‘‘ and segment_name =‘‘table_name‘‘;
562 
563 ############ UNDO Data ################
564 
565 show parameter undo;
566 
567 alter tablespace users offline normal;
568 
569 alter tablespace users offline immediate;
570 
571 recover datafile ‘‘$ORACLE_HOME/oradata/undo102.dbf‘‘;
572 
573 alter tablespace users online ;
574 
575 select * from dba_rollback_segs;
576 
577 alter system set undo_tablespace=undotbs1;
578 
579 /*忽略回滚段的错误提示*/
580 alter system set undo_suppress_errors=true;
581 
582 /*在自动管理模式下,不会真正建立rbs1;在手工管理模式则可以建立,且是私有回滚段*/
583 create rollback segment rbs1 tablespace undotbs;
584 
585 desc dbms_flashback;
586 
587 /*在提交了修改的数据后,9i提供了旧数据的回闪操作,将修改前的数据只读给用户看,但这部分数据不会又恢复在表中,而是旧数据的一个映射*/
588 execute dbms_flashback.enable_at_time(‘‘26-JAN-04:12:17:00 pm‘‘);
589 
590 execute dbms_flashback.disable;
591 
592 /*回滚段的统计信息*/
593 select end_time,begin_time,undoblks from v$undostat;
594 
595 /*undo表空间的大小计算公式: UndoSpace=[UR * (UPS * DBS)] + (DBS * 24)
596 UR :UNDO_RETENTION 保留的时间(秒)
597 UPS :每秒的回滚数据块
598 DBS:系统EXTENT和FILE SIZE(也就是db_block_size)*/
599 
600 select * from dba_rollback_segs/v$rollname/v$rollstat/v$undostat/v$session/v$transaction;
601 
602 show parameter transactions;
603 
604 show parameter rollback;
605 
606 /*在手工管理模式下,建立公共的回滚段*/
607 create public rollback segment prbs1 tablespace undotbs;
608 
609 alter rollback segment rbs1 online;----在手工管理模式 
610 
611 /*在手工管理模式中,initSID.ora中指定 undo_management=manual 、rollback_segment=(‘‘rbs1‘‘,‘‘rbs2‘‘,...)、
612 transactions=100 、transactions_per_rollback_segment=10
613 然后 shutdown immediate ,startup pfile=....\???.ora */
614 
615 ########## Managing Tables ###########
616 
617 /*char type maxlen=2000;varchar2 type maxlen=4000 bytes
618 rowid 是18位的64进制字符串 (10个bytes 80 bits)
619 rowid组成: object#(对象号)--32bits,6位
620 rfile#(相对文件号)--10bits,3位
621 block#(块号)--22bits,6位
622 row#(行号)--16bits,3位
623 64进制: A-Z,a-z,0-9,/,+ 共64个符号
624 
625 dbms_rowid 包中的函数可以提供对rowid的解释*/
626 
627 select rowid,dbms_rowid.rowid_block_number(rowid),dbms_rowid.rowid_row_number(rowid) from table_name;
628 
629 create table test2
630 (
631 id int,
632 lname varchar2(20) not null,
633 fname varchar2(20) constraint ck_1 check(fname like‘k%‘‘),
634 empdate date default sysdate)
635 ) tablespace tablespace_name;
636 
637 
638 create global temporary table test2 on commit delete/preserve rows as select * from kong.authors;
639 
640 create table user.table(...) tablespace tablespace_name storage(...) pctfree10 pctused 40;
641 
642 alter table user.tablename pctfree 20 pctused 50 storage(...);---changing table storage 
643 
644 /*手工分配分区,分配的数据文件必须是表所在表空间内的数据文件*/
645 alter table user.table_name allocate extent(size 500k datafile ‘‘...‘‘);
646 
647 /*释放表中没有用到的空间*/
648 alter table table_name deallocate unused;
649 
650 alter table table_name deallocate unused keep 8k;
651 
652 /*将非分区表的表空间搬到新的表空间,在移动表空间后,原表中的索引对象将会不可用,必须重建*/
653 alter table user.table_name move tablespace new_tablespace_name;
654 
655 create index index_name on user.table_name(column_name) tablespace users;
656 
657 alter index index_name rebuild;
658 
659 drop table table_name [CASCADE CONSTRAINTS];
660 
661 alter table user.table_name drop column col_name [CASCADE CONSTRAINTS CHECKPOINT 1000];---drop column 
662 
663 /*给表中不用的列做标记*/
664 alter table user.table_name set unused column comments CASCADE CONSTRAINTS;
665 
666 /*drop表中不用的做了标记列*/
667 alter table user.table_name drop unused columns checkpoint 1000;
668 
669 /*当在drop col是出现异常,使用CONTINUE,防止重删前面的column*/
670 ALTER TABLE USER.TABLE_NAME DROP COLUMNS CONTINUE CHECKPOINT 1000;
671 
672 select * from dba_tables/dba_objects;
673 
674 ######## managing indexes ##########
675 
676 /*create index*/
677 example:
678 /*创建一般索引*/
679 create index index_name on table_name(column_name) tablespace tablespace_name;
680 /*创建位图索引*/
681 create bitmap index index_name on table_name(column_name1,column_name2) tablespace tablespace_name;
682 /*索引中不能用pctused*/
683 create [bitmap] index index_name on table_name(column_name) tablespace tablespace_name pctfree 20 storage(inital 100k next 100k) ;
684 /*大数据量的索引最好不要做日志*/
685 create [bitmap] index index_name table_name(column_name1,column_name2) tablespace_name pctfree 20 storage(inital 100k next 100k) nologging;
686 /*创建反转索引*/
687 create index index_name on table_name(column_name) reverse;
688 /*创建函数索引*/
689 create index index_name on table_name(function_name(column_name)) tablespace tablespace_name;
690 /*建表时创建约束条件*/
691 create table user.table_name(column_name number(7) constraint constraint_name primary key deferrable using index storage(initial 100k next 100k) tablespace tablespace_name,column_name2 varchar2(25) constraint constraint_name not null,column_name3 number(7)) tablespace tablespace_name;
692 
693 /*给创建bitmap index分配的内存空间参数,以加速建索引*/
694 show parameter create_bit;
695 
696 /*改变索引的存储参数*/
697 alter index index_name pctfree 30 storage(initial 200k next 200k);
698 
699 /*给索引手工分配一个分区*/
700 alter index index_name allocate extent (size 200k datafile ‘‘$ORACLE/oradata/..‘‘);
701 
702 /*释放索引中没用的空间*/
703 alter index index_name deallocate unused;
704 
705 /*索引重建*/
706 alter index index_name rebuild tablespace tablespace_name;
707 
708 /*普通索引和反转索引的互换*/
709 alter index index_name rebuild tablespace tablespace_name reverse;
710 
711 /*重建索引时,不锁表*/
712 alter index index_name rebuild online;
713 
714 /*给索引整理碎片*/
715 alter index index_name COALESCE;
716 
717 /*分析索引,事实上是更新统计的过程*/
718 analyze index index_name validate structure;
719 
720 desc index_state;
721 
722 drop index index_name;
723 
724 alter index index_name monitoring usage;-----监视索引是否被用到 
725 
726 alter index index_name nomonitoring usage;----取消监视 
727 
728 /*有关索引信息的视图*/
729 select * from dba_indexes/dba_ind_columns/dbs_ind_expressions/v$object_usage;
730 
731 ########## 数据完整性的管理(Maintaining data integrity) ##########
732 
733 alter table table_name drop constraint constraint_name;----drop 约束 
734 
735 alter table table_name add constraint constraint_name primary key(column_name1,column_name2);-----创建主键 
736 
737 alter table table_name add constraint constraint_name unique(column_name1,column_name2);---创建唯一约束 
738 
739 /*创建外键约束*/
740 alter table table_name add constraint constraint_name foreign key(column_name1) references table_name(column_name1);
741 
742 /*不效验老数据,只约束新的数据[enable/disable:约束/不约束新数据;novalidate/validate:不对/对老数据进行验证]*/
743 alter table table_name add constraint constraint_name check(column_name like‘B%‘‘) enable/disable novalidate/validate;
744 
745 /*修改约束条件,延时验证,commit时验证*/
746 alter table table_name modify constraint constraint_name initially deferred;
747 
748 /*修改约束条件,立即验证*/
749 alter table table_name modify constraint constraint_name initially immediate;
750 
751 alter session set constraints=deferred/immediate;
752 
753 /*drop一个有外键的主键表,带cascade constraints参数级联删除*/
754 drop table table_name cascade constraints;
755 
756 /*当truncate外键表时,先将外键设为无效,再truncate;*/
757 truncate table table_name;
758 
759 /*设约束条件无效*/
760 alter table table_name disable constraint constraint_name;
761 
762 alter table table_name enable novalidate constraint constraint_name;
763 
764 /*将无效约束的数据行放入exception的表中,此表记录了违反数据约束的行的行号;在此之前,要先建exceptions表*/
765 alter table table_name add constraint constraint_name check(column_name >15) enable validate exceptions into exceptions;
766 
767 /*运行创建exceptions表的脚本*/
768 start $ORACLE_HOME/rdbms/admin/utlexcpt.sql;
769 
770 /*获取约束条件信息的表或视图*/
771 select * from user_constraints/dba_constraints/dba_cons_columns;
772 
773 ################## managing password security and resources ####################
774 
775 alter user user_name account unlock/open;----锁定/打开用户; 
776 
777 alter user user_name password expire;---设定口令到期 
778 
779 /*建立口令配置文件,failed_login_attempts口令输多少次后锁,password_lock_times指多少天后口令被自动解锁*/
780 create profile profile_name limit failed_login_attempts 3 password_lock_times 1/1440;
781 /*创建口令配置文件*/
782 create profile profile_name limit failed_login_attempts 3 password_lock_time unlimited password_life_time 30 password_reuse_time 30 password_verify_function verify_function password_grace_time 5;
783 /*建立资源配置文件*/
784 create profile prfile_name limit session_per_user 2 cpu_per_session 10000 idle_time 60 connect_time 480;
785 
786 alter user user_name profile profile_name;
787 
788 /*设置口令解锁时间*/
789 alter profile profile_name limit password_lock_time 1/24;
790 
791 /*password_life_time指口令文件多少时间到期,password_grace_time指在第一次成功登录后到口令到期有多少天时间可改变口令*/
792 alter profile profile_name limit password_lift_time 2 password_grace_time 3;
793 
794 /*password_reuse_time指口令在多少天内可被重用,password_reuse_max口令可被重用的最大次数*/
795 alter profile profile_name limit password_reuse_time 10[password_reuse_max 3];
796 
797 alter user user_name identified by input_password;-----修改用户口令 
798 
799 drop profile profile_name;
800 
801 /*建立了profile后,且指定给某个用户,则必须用CASCADE才能删除*/
802 drop profile profile_name CASCADE;
803 
804 alter system set resource_limit=true;---启用自愿限制,缺省是false 
805 
806 /*配置资源参数*/
807 alter profile profile_name limit cpu_per_session 10000 connect_time 60 idle_time 5;
808 /*资源参数(session级)
809 cpu_per_session 每个session占用cpu的时间 单位1/100秒
810 sessions_per_user 允许每个用户的并行session数
811 connect_time 允许连接的时间 单位分钟
812 idle_time 连接被空闲多少时间后,被自动断开 单位分钟
813 logical_reads_per_session 读块数
814 ***_sga 用户能够在SGA中使用的私有的空间数 单位bytes
815 
816 (call级)
817 cpu_per_call 每次(1/100秒)调用cpu的时间
818 logical_reads_per_call 每次调用能够读的块数
819 */
820 
821 alter profile profile_name limit cpu_per_call 1000 logical_reads_per_call 10;
822 
823 desc dbms_resouce_manager;---资源管理器包 
824 
825 /*获取资源信息的表或视图*/
826 select * from dba_users/dba_profiles;
827 
828 ###### Managing users ############
829 
830 show parameter os;
831 
832 create user testuser1 identified by kxf_001;
833 
834 grant connect,createtable to testuser1;
835 
836 alter user testuser1 quota 10m on tablespace_name;
837 
838 /*创建用户*/
839 create user user_name identified by password default tablespace tablespace_name temporary tablespace tablespace_name quota 15m on tablespace_name password expire;
840 
841 /*数据库级设定缺省临时表空间*/
842 alter database default temporary tablespace tablespace_name;
843 
844 /*制定数据库级的缺省表空间*/
845 alter database default tablespace tablespace_name;
846 
847 /*创建os级审核的用户,需知道os_authent_prefix,表示oracle和os口令对应的前缀,‘‘OPS$‘‘为此参数的值,此值可以任意设置*/
848 create user user_name identified by externally default OPS$tablespace_name tablespace_name temporary tablespace tablespace_name quota 15m on tablespace_name password expire;
849 
850 /*修改用户使用表空间的限额,回滚表空间和临时表空间不允许授予限额*/
851 alter user user_name quota 5m on tablespace_name;
852 
853 /*删除用户或删除级联用户(用户对象下有对象的要用CASCADE,将其下一些对象一起删除)*/
854 drop user user_name [CASCADE];
855 
856 /*每个用户在哪些表空间下有些什么限额*/
857 desc dba_ts_quotas;select * from dba_ts_quotas where username=‘‘...‘‘;
858 
859 /*改变用户的缺省表空间*/
860 alter user user_name default tablespace tablespace_name;
861 
862 ######### Managing Privileges #############
863 
864 grant create table,create session to user_name;
865 
866 grant create any table to user_name; revoke create any table from user_name;
867 
868 /*授予权限语法,public 标识所有用户,with admin option允许能将权限授予第三者的权限*/
869 grant system_privs,[......] to [user/role/public],[....] [with admin option];
870 
871 select * from v$pwfile_users;
872 
873 /*当 O7_dictionary_accessiblity参数为True时,标识select any table时,包括系统表也能select ,否则,不包含系统表;缺省为false*/
874 show parameter O7;
875 
876 /*由于 O7_dictionary_accessiblity为静态参数,不能动态改变,故加scope=spfile,下次启动时才生效*/
877 alter system set O7_dictionary_accessiblity=true scope=spfile;
878 
879 /*授予对象中的某些字段的权限,如select 某表中的某些字段的权限*/
880 grant [object_privs(column,....)],[...] on object_name to user/role/public,... with grant option;
881 
882 /*oracle不允许授予select某列的权限,但可以授insert ,update某列的权限*/
883 grant insert(column_name1,column_name2,...) on table_name to user_name with grant option;
884 
885 select * from dba_sys_privs/session_privs/dba_tab_privs/user_tab_privs/dba_col_privs/user_col_privs;
886 
887 /*db/os/none 审计被记录在 数据库/操作系统/不审计 缺省是none*/
888 show parameter audit_trail;
889 
890 /*启动对表的select动作*/
891 audit select on user.table_name by session;
892 
893 /*by session在每个session中发出command只记录一次,by access则每个command都记录*/
894 audit [create table][select/update/insert on object by session/access][whenever successful/not successful];
895 
896 desc dbms_fga;---进一步设计,则可使用dbms_fgs包 
897 
898 /*取消审计*/
899 noaudit select on user.table_name;
900 
901 /*查被审计信息*/
902 select * from all_def_audit_opts/dba_stmt_audit_opts/dba_priv_audit_opts/dba_obj_audit_opts;
903 
904 /*获取审计记录*/
905 select * from dba_audit_trail/dba_audit_exists/dba_audit_object/dba_audit_session/dba_audit_statement;
906 
907 ########### Managing Role #################
908 
909 create role role_name; grant select on table_name to role_name; grant role_name to user_name; set role role_name;
910 
911 create role role_name;
912 create role role_name identified by password;
913 create role role_name identified externally;
914 
915 set role role_name ; ----激活role 
916 set role role_name identified by password;
917 
918 alter role role_name not identified;
919 alter role role_name identified by password;
920 alter role role_name identified externally;
921 
922 grant priv_name to role_name [WITH ADMIN OPTION];
923 grant update(column_name1,col_name2,...) on table_name to role_name;
924 grant role_name1 to role_name2;
925 
926 /*建立default role,用户登录时,缺省激活default role*/
927 alter user user_name default role role_name1,role_name2,...;
928 alter user user_name default role all;
929 alter user user_name default role all except role_name1,...;
930 alter user user_name default role none;
931 
932 set role role1 [identified by password],role2,....;
933 set role all;
934 set role except role1,role2,...;
935 set role none;
936 
937 revoke role_name from user_name;
938 revoke role_name from public;
939 
940 drop role role_name;
941 
942 select * from dba_roles/dba_role_privs/role_role_privs/dba_sys_privs/role_sys_privs/role_tab_privs/session_roles;
943 
944 ########### Basic SQL SELECT ################
945 
946 select col_name as col_alias from table_name ;
947 
948 select col_name from table_name where col1 like‘_o%‘‘; ----‘‘_‘‘匹配单个字符 
949 
950 /*使用字符函数(右边截取,字段中包含某个字符,左边填充某字符到固定位数,右边填充某字符到固定位数)*/
951 select substr(col1,-3,5),instr(col2,‘‘g‘‘),LPAD(col3,10,‘‘$‘‘),RPAD(col4,10,‘‘%‘‘) from table_name;
952 
953 /*使用数字函数(往右/左几位四舍五入,取整,取余)*/
954 select round(col1,-2),trunc(col2),mod(col3) from table_name ;
955 
956 /*使用日期函数(计算两个日期间相差几个星期,两个日期间相隔几个月,在某个月份上加几个月,某个日期的下一个日期,
957 某日期所在月的最后的日期,对某个日期的月分四舍五入,对某个日期的月份进行取整)*/
958 select (sysdate-col1)/7 week,months_between(sysdate,col1),add_months(col1,2),next_day(sysdate,‘‘FRIDAY‘‘),last_day(sysdate),
959 round(sysdate,‘‘MONTH‘‘),trunc(sysdate,‘‘MONTH‘‘) from table_name;
960 
961 /*使用NULL函数(当expr1为空取expr2/当expr1为空取expr2,否则取expr3/当expr1=expr2返回空)*/
962 select nvl(expr1,expr2),nvl2(expr1,expr2,expr3),nullif(expr1,expr2) from table_name;
963 
964 select column1,column2,column3, case column2 when‘50‘then column2*1.1
965 when‘30‘then column2*2.1
966 when‘10‘then column3/20
967 else column3
968 end as ttt
969 from table_name ; ------使用case函数 
970 
971 select table1.col1,table2.col2 from table1
972 [CROSS JOIN table2] | -----笛卡儿连接 
973 [NATURAL JOIN table2] | -----用两个表中的同名列连接 
974 [JOIN table2 USING (column_name)] | -----用两个表中的同名列中的某一列或几列连接 
975 [JOIN table2
976 ON (table1.col1=table2.col2)] |
977 [LEFT|RIGHT|FULL OUTER JOIN table2 ------相当于(+)=,=(+)连接,全外连接 
978 ON (table1.col1=table2.col2)]; ------SQL 1999中的JOIN语法; 
979 
980 example:
981 select col1,col2 from table1 t1
982 join table2 t2
983 on t1.col1=t2.col2 and t1.col3=t2.col1
984 join table3 t3
985 on t2.col1=t3.col3;
986 
987 select * from table_name where col1 < any (select col2 from table_name2 where continue group by col3);
988 
989 select * from table_name where col1 < all (select col2 from table_name2 where continue group by col3);
990 
991 insert into (select col1,col2,col3 form table_name where col1> 50 with check option) values (value1,value2,value3);
992 
993 MERGE INTO table_name table1
994 USING table_name2 table2
995 ON (table1.col1=table2.col2)
996 WHEN MATCHED THEN
997 UPDATE SET
998 table1.col1=table2.col2,
999 table1.col2=table2.col3,
1000 ...
1001 WHEN NOT MATCHED THEN
1002 INSERT VALUES(table2.col1,table2.col2,table2.col3,...); -----合并语句 
1003 
1004 ##################### CREATE/ALTER TABLE #######################
1005 
1006 alter table table_name drop column column_name ;---drop column 
1007 
1008 alter table table_name set unused (col1,col2,...);----设置列无效,这个比较快。 
1009 alter table table_name drop unused columns;---删除被设为无效的列 
1010 
1011 rename table_name1 to table_name2; ---重命名表 
1012 
1013 comment on table table_name is‘comment message‘‘;----给表放入注释信息 
1014 
1015 create table table_name
1016 (col1 int not null,col2 varchar2(20),col3 varchar2(20),
1017 constraint uk_test2_1 unique(col2,col3))); -----定义表中的约束条件 
1018 
1019 alter table table_name add constraint pk_test2 primary key(col1,col2,...); ----创建主键 
1020 
1021 /*建立外键*/
1022 create table table_name (rid int,name varchar2(20),constraint fk_test3 foreign key(rid) references other_table_name(id));
1023 
1024 alter table table_name add constraint ck_test3 check(name like‘K%‘‘);
1025 
1026 alter table table_name drop constraint constraint_name;
1027 
1028 alter table table_name drop primary key cascade;----级联删除主键 
1029 
1030 alter table table_name disable/enable constraint constraint_name;----使约束暂时无效 
1031 
1032 /*删除列,并级联删除此列下的约束条件*/
1033 alter table table_name drop column column_name cascade constraint;
1034 
1035 select * from user_constraints/user_cons_columns;---约束条件相关视图 
1036 
1037 ############## Create Views #####################
1038 
1039 CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view_name [(alias[,alias]...)]
1040 AS subquery
1041 [WITH CHECK OPTION [CONSTRAINT constraint_name]]
1042 [WITH READ ONLY [CONSTRAINT constraint_name]]; ------创建视图的语法 
1043 
1044 example: Create or replace view testview as select col1,col2,col3 from table_name; ------创建视图 
1045 /*使用别名*/
1046 Create or replace view testview as select col1,sum(col2) col2_alias from table_name;
1047 /*创建复杂视图*/
1048 Create view view_name (alias1,alias2,alias3,alias4) as select d.col1,min(e.col1),max(e.col1),***g(e.col1) from table_name1 e,table_name2 d where e.col2=d.col2 group by d.col1;
1049 /*当用update修改数据时,必须满足视图的col1>10的条件,不满足则不能被改变.*/
1050 Create or replace view view_name as select * from table_name where col1>10 with check option;
1051 
1052 /*改变视图的值.对于简单视图可以用update语法修改表数据,但复杂视图则不一定能改。如使用了函数,group by ,distinct等的列*/
1053 update view_name set col1=value1;
1054 
1055 /*TOP-N分析*/
1056 select [column_list],rownum from (select [column_list] from table_name order by Top-N_column) where rownum<=N;
1057 
1058 /*找出某列三条最大值的记录*/
1059 example: select rownum as rank ,col1 ,col2 from (select col1 ,col2 from table_name order by col2 desc) where rownum<=3;
1060 
1061 ############# Other database Object ###############
1062 
1063 CREATE SEQUENCE sequence_name [INCREMENT BY n]
1064 [START WITH n]
1065 [{MAXVALUE n | NOMAXVALUE}]
1066 [{MINVALUE n | NOMINVALUE}]
1067 [{CYCEL | NOCYCLE}]
1068 [{CACHE n | NOCACHE}]; -----创建SEQUENCE 
1069 
1070 example:
1071 CREATE SEQUENCE sequence_name INCREMENT BY 10
1072 START WITH 120
1073 MAXVALUE 9999
1074 NOCACHE
1075 NOCYCLE;
1076 
1077 select * from user_sequences ;---当前用户下记录sequence的视图 
1078 
1079 select sequence_name.nextval,sequence_name.currval from dual;-----sequence的引用 
1080 
1081 alter sequence sequence_name INCREMENT BY 20
1082 MAXVALUE 999999
1083 NOCACHE
1084 NOCYCLE; -----修改sequence,不能改变起始序号 
1085 
1086 drop sequence sequence_name; ----删除sequence 
1087 
1088 CREATE [PUBLIC] SYNONYM synonym_name FOR object; ------创建同义词 
1089 
1090 DROP [PUBLIC] SYNONYM synonym_name;----删除同义词 
1091 
1092 CREATE PUBLIC DATABASE LINK link_name USEING OBJECT;----创建DBLINK 
1093 
1094 select * from object_name@link_name; ----访问远程数据库中的对象 
1095 
1096 /*union 操作,它将两个集合的交集部分压缩,并对数据排序*/
1097 select col1,col2,col3 from table1_name union select col1,col2,col3 from table2_name;
1098 
1099 /*union all 操作,两个集合的交集部分不压缩,且不对数据排序*/
1100 select col1,col2,col3 from table1_name union all select col1,col2,col3 from table2_name;
1101 
1102 /*intersect 操作,求两个集合的交集,它将对重复数据进行压缩,且排序*/
1103 select col1,col2,col3 from table1_name intersect select col1,col2,col3 from table2_name;
1104 
1105 /*minus 操作,集合减,它将压缩两个集合减后的重复记录, 且对数据排序*/
1106 select col1,col2,col3 from table1_name minus select col1,col2,col3 from table2_name;
1107 
1108 /*EXTRACT 抽取时间函数. 此例是抽取当前日期中的年*/
1109 select EXTRACT(YEAR FROM SYSDATE) from dual;
1110 /*EXTRACT 抽取时间函数. 此例是抽取当前日期中的月*/
1111 select EXTRACT(MONTH FROM SYSDATE) from dual;
1112 
1113 ########################## 增强的 group by 子句 #########################
1114 
1115 select [column,] group_function(column)...
1116 from table
1117 [WHERE condition]
1118 [GROUP BY [ROLLUP] group_by_expression]
1119 [H***ING h***ing_expression];
1120 [ORDER BY column]; -------ROLLUP操作字,对group by子句的各字段从右到左进行再聚合 
1121 
1122 example:
1123 /*其结果看起来象对col1做小计*/
1124 select col1,col2,sum(col3) from table group by rollup(col1,col2);
1125 /*复合rollup表达式*/
1126 select col1,col2,sum(col3) from table group by rollup((col1,col2));
1127 
1128 select [column,] group_function(column)...
1129 from table
1130 [WHERE condition]
1131 [GROUP BY [CUBE] group_by_expression]
1132 [H***ING h***ing_expression];
1133 [ORDER BY column]; -------CUBE操作字,除完成ROLLUP的功能外,再对ROLLUP后的结果集从右到左再聚合 
1134 
1135 example:
1136 /*其结果看起来象对col1做小计后,再对col2做小计,最后算总计*/
1137 select col1,col2,sum(col3) from table group by cube(col1,col2);
1138 /*复合rollup表达式*/
1139 select col1,col2,sum(col3) from table group by cube((col1,col2));
1140 /*混合rollup,cube表达式*/
1141 select col1,col2,col3,sum(col4) from table group by col1,rollup(col2),cube(col3);
1142 
1143 /*GROUPING(expr)函数,查看select语句种以何字段聚合,其取值为0或1*/
1144 select [column,] group_function(column)...,GROUPING(expr)
1145 from table
1146 [WHERE condition]
1147 [GROUP BY [ROLLUP] group_by_expression]
1148 [H***ING h***ing_expression];
1149 [ORDER BY column];
1150 
1151 example:
1152 select col1,col2,sum(col3),grouping(col1),grouping(col2) from table group by cube(col1,col2);
1153 
1154 /*grouping sets操作,对group by结果集先对col1求和,再对col2求和,最后将其结果集并在一起*/
1155 select col1,col2,sum(col3) from table group by grouping sets((col1),(col2));
1156 
1157 

oracle常用经典SQL查询

标签:output   locate   proc   stat   outer   ret   arch   process   art   

原文地址:http://www.cnblogs.com/ios9/p/7449898.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!