--获取当前月份的第一天 

SELECT TRUNC (SYSDATE, 'MONTH') "First day of current month" 
    FROM DUAL;
    
--获取当前月份的最后一天

SELECT TRUNC (LAST_DAY (SYSDATE)) "Last day of current month" 
    FROM DUAL;
    
--获取当前年份的第一天

SELECT TRUNC (SYSDATE, 'YEAR') "Year First Day" FROM DUAL;

--获取当前年份的最后一天
SELECT ADD_MONTHS (TRUNC (SYSDATE, 'YEAR'), 12) - 1 "Year Last Day" FROM DUAL;

--获取当前月份的天数

SELECT CAST (TO_CHAR (LAST_DAY (SYSDATE), 'dd') AS INT) number_of_days  FROM DUAL; 
--获取当前月份剩下的天数

 SELECT SYSDATE,  
        LAST_DAY (SYSDATE) "Last",  
        LAST_DAY (SYSDATE) - SYSDATE "Days left" 
   FROM DUAL; 

--获取两个日期之间的天数

SELECT ROUND ((MONTHS_BETWEEN ('01-Feb-2014', '01-Mar-2012') * 30), 0) num_of_days FROM DUAL;  
OR 
SELECT TRUNC(sysdate) - TRUNC(e.hire_date) FROM employees; 

--显示当前年份截止到本月每个月份开始和结束的日期


SELECT ADD_MONTHS (TRUNC (SYSDATE, 'MONTH'), i) start_date,
       TRUNC (LAST_DAY (ADD_MONTHS (SYSDATE, i))) end_date
  FROM XMLTABLE (
          'for $i in 0 to xs:int(D) return $i'
          PASSING XMLELEMENT (
                     d,
                     FLOOR (
                        MONTHS_BETWEEN (
                           ADD_MONTHS (TRUNC (SYSDATE, 'YEAR') - 1, 12),
                           SYSDATE)))
          COLUMNS i INTEGER PATH '.');
--把数值转换成文字

SELECT TO_CHAR (TO_DATE (1526, 'j'), 'jsp') FROM DUAL;

--获取拥有者的对象数量


SELECT owner, COUNT (owner) number_of_objects
    FROM dba_objects
GROUP BY owner
ORDER BY number_of_objects DESC;

--查询并显示连接 Oracle 的用户和用户的会话数量


SELECT username Usuario_Oracle, COUNT (username) Numero_Sesiones
    FROM v$session
GROUP BY username
ORDER BY Numero_Sesiones DESC;

--查询并显示通过打开连接程序打开连接的组


SELECT program application, COUNT (program) Numero_Sesiones
    FROM v$session
GROUP BY program
ORDER BY Numero_Sesiones DESC;

--在视图中查询并显示实际的 Oracle 连接 


SELECT osuser,
         username,
         machine,
         program
    FROM v$session
ORDER BY osuser;

--查询每个执行读取的前十个 SQL 

SELECT *
  FROM (  SELECT ROWNUM,
                 SUBSTR (a.sql_text, 1, 200) sql_text,
                 TRUNC (
                    a.disk_reads / DECODE (a.executions, 0, 1, a.executions))
                    reads_per_execution,
                 a.buffer_gets,
                 a.disk_reads,
                 a.executions,
                 a.sorts,
                 a.address
            FROM v$sqlarea a
        ORDER BY 3 DESC)
 WHERE ROWNUM < 10;
 
 --查询特定的模式或者表中执行的最后一个 SQL 语句 
 
 
SELECT CREATED, TIMESTAMP, last_ddl_time
  FROM all_objects
 WHERE     OWNER = 'MYSCHEMA'
       AND OBJECT_TYPE = 'TABLE'
       AND OBJECT_NAME = 'EMPLOYEE_TABLE';
       
--获取当前会话 ID,进程 ID,客户端 ID 等 

SELECT b.sid,
       b.serial#,
       a.spid processid,
       b.process clientpid
  FROM v$process a, v$session b
 WHERE a.addr = b.paddr AND b.audsid = USERENV ('sessionid');
 
--查询数据库长查询进展情况


SELECT a.sid,
         a.serial#,
         b.username,
         opname OPERATION,
         target OBJECT,
         TRUNC (elapsed_seconds, 5) "ET (s)",
         TO_CHAR (start_time, 'HH24:MI:SS') start_time,
         ROUND ( (sofar / totalwork) * 100, 2) "COMPLETE (%)"
    FROM v$session_longops a, v$session b
   WHERE     a.sid = b.sid
         AND b.username NOT IN ('SYS', 'SYSTEM')
         AND totalwork > 0
ORDER BY elapsed_seconds;

--查询用户 CPU 的使用率 


SELECT ss.username, se.SID, VALUE / 100 cpu_usage_seconds
    FROM v$session ss, v$sesstat se, v$statname sn
   WHERE     se.STATISTIC# = sn.STATISTIC#
         AND NAME LIKE '%CPU used by this session%'
         AND se.SID = ss.SID
         AND ss.status = 'ACTIVE'
         AND ss.username IS NOT NULL
ORDER BY VALUE DESC;

--查询数据库中每个用户最后使用的 SQL 查询 

SELECT S.USERNAME || '(' || s.sid || ')-' || s.osuser UNAME,
         s.program || '-' || s.terminal || '(' || s.machine || ')' PROG,
         s.sid || '/' || s.serial# sid,
         s.status "Status",
         p.spid,
         sql_text sqltext
    FROM v$sqltext_with_newlines t, V$SESSION s, v$process p
   WHERE     t.address = s.sql_address
         AND p.addr = s.paddr(+)
         AND t.hash_value = s.sql_hash_value
ORDER BY s.sid, t.piece;

--查询模式或者用户的大小


SELECT SUM (bytes / 1024 / 1024) "size"
  FROM dba_segments
 WHERE owner = '&owner';
 
--查询数据库中数据占用的大小或者是数据库使用细节


SELECT SUM (bytes) / 1024 / 1024 / 1024 AS GB FROM dba_segments;

--查询数据库的实际大小


SELECT SUM (bytes) / 1024 / 1024 / 1024 AS GB FROM dba_data_files;

--增加数据文件的大小


ALTER DATABASE DATAFILE '/u01/app/Test_data_01.dbf' RESIZE 2G;

--在表空间添加数据文件


ALTER TABLESPACE data01 ADD DATAFILE '/work/oradata/STARTST/data01.dbf'
    SIZE 1000M AUTOEXTEND OFF;
    
--检查表空间的自动扩展开关 



SELECT SUBSTR (file_name, 1, 50), AUTOEXTENSIBLE FROM dba_data_files;
(OR)
SELECT tablespace_name, AUTOEXTENSIBLE FROM dba_data_files;

--调整没有添加数据文件的表空间


ALTER DATABASE DATAFILE '/work/oradata/STARTST/STAR02D.dbf' resize 2000M;

--存储区分大小写的数据,但是索引不区分大小写


CREATE TABLE tab (col1 VARCHAR2 (10));
CREATE INDEX idx1
   ON tab (UPPER (col1));
ANALYZE TABLE a COMPUTE STATISTICS;

--获取 Oracle 版本


SELECT VALUE
  FROM v$system_parameter
 WHERE name = 'compatible';


--数据库字符设置信息


SELECT * FROM nls_database_parameters;

--数据库默认信息 


SELECT username,
       profile,
       default_tablespace,
       temporary_tablespace
  FROM dba_users;
  
--数据库版本信息


SELECT * FROM v$version;

--修改当前模式


ALTER SESSION SET CURRENT_SCHEMA = new_schema;

--获取当前模式


SELECT SYS_CONTEXT ('userenv', 'current_schema') FROM DUAL;

--显示表结构


SELECT DBMS_METADATA.get_ddl ('TABLE', 'TABLE_NAME', 'USER_NAME') FROM DUAL;

--检查在当前表中是否存在指定的列


SELECT column_name AS FOUND
  FROM user_tab_cols
 WHERE table_name = 'TABLE_NAME' AND column_name = 'COLUMN_NAME';
 
--检查在当前数据库模式下是否存在指定的表


SELECT table_name
  FROM user_tables
 WHERE table_name = 'TABLE_NAME';
 
--获取今天剩下的秒数(直到 23:59:59 结束)
 
 SELECT (TRUNC (SYSDATE+1) - SYSDATE) * 24 * 60 * 60 num_of_sec_left FROM DUAL; 
 
--获取直到目前为止今天过去的秒数(从 00:00 开始算)

SELECT (SYSDATE - TRUNC (SYSDATE)) * 24 * 60 * 60 num_of_sec_since_morning FROM DUAL;


--在包的源代码中查询字符串  search a string foo_something in package source code

SELECT *
  FROM dba_source
 WHERE UPPER (text) LIKE '%FOO_SOMETHING%' 
AND owner = 'USER_NAME';

--把用逗号分隔的数据插入的表中

WITH csv
     AS (SELECT 'AA,BB,CC,DD,EE,FF'
                   AS csvdata
           FROM DUAL)
    SELECT REGEXP_SUBSTR (csv.csvdata, '[^,]+', 1, LEVEL) pivot_char
      FROM DUAL, csv
CONNECT BY REGEXP_SUBSTR (csv.csvdata,'[^,]+', 1, LEVEL) IS NOT NULL;

--查询表中的最后一个记录

SELECT *
  FROM employees
 WHERE ROWID IN (SELECT MAX (ROWID) FROM employees);
(OR)
SELECT * FROM employees
MINUS
SELECT *
  FROM employees
 WHERE ROWNUM < (SELECT COUNT (*) FROM employees);
 
--在 Oracle 中做行数据乘法

WITH tbl
     AS (SELECT -2 num FROM DUAL
         UNION
         SELECT -3 num FROM DUAL
         UNION
         SELECT -4 num FROM DUAL),
     sign_val
     AS (SELECT CASE MOD (COUNT (*), 2) WHEN 0 THEN 1 ELSE -1 END val
           FROM tbl
          WHERE num < 0)
  SELECT EXP (SUM (LN (ABS (num)))) * val
    FROM tbl, sign_val
GROUP BY val;

--在 Oracle 中生成随机数值   generate random number between 0 and 100 

SELECT ROUND (DBMS_RANDOM.VALUE () * 100) + 1 AS random_num FROM DUAL; 

--在 Oracle 生成随机数据

SELECT LEVEL empl_id,
           MOD (ROWNUM, 50000) dept_id,
           TRUNC (DBMS_RANDOM.VALUE (1000, 500000), 2) salary,
           DECODE (ROUND (DBMS_RANDOM.VALUE (1, 2)),  1, 'M',  2, 'F') gender,
           TO_DATE (
                 ROUND (DBMS_RANDOM.VALUE (1, 28))
              || '-'
              || ROUND (DBMS_RANDOM.VALUE (1, 12))
              || '-'
              || ROUND (DBMS_RANDOM.VALUE (1900, 2010)),
              'DD-MM-YYYY')
              dob,
           DBMS_RANDOM.STRING ('x', DBMS_RANDOM.VALUE (20, 50)) address
      FROM DUAL
CONNECT BY LEVEL < 10000;