# 一、元数据 ## 1.1 存储过程 + 查看所有存储过程 ```sql select distinct name From user_source where type = 'PROCEDURE' ``` + 查看存储过程语句 ```sql SELECT text FROM user_source WHERE NAME = 'EXECUTE_JOB_FINANCE_SURVEY' ORDER BY line ``` ## 1.2 表 + 查看所有表 ```sql # 查询当前用户 select * from user_tab_comments where table_type='TABLE'; # 查询所有用户,当前用户必须有sysdba权限 select * from all_tab_comments ``` + 查看表所有字段 ```sql SELECT COLUMN_NAME, DATA_TYPE FROM user_tab_columns WHERE table_name = 'DW_INFRASTRUCTURE_SURVEY' ORDER BY COLUMN_ID ASC; ``` + 查看具体字段 ```sql SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH, NULLABLE, DEFAULT_LENGTH, DATA_DEFAULT FROM user_tab_columns WHERE table_name = 'DW_INFRASTRUCTURE_SURVEY' AND COLUMN_NAME = 'STATISTICAL_TIME' ORDER BY COLUMN_ID ASC; ``` + 查看字段及注释 ```sql SELECT b.COLUMN_NAME, a.COMMENTS, case when DATA_PRECISION is null and DATA_SCALE=0 and DATA_TYPE='NUMBER' then 'NUMBER(38,0)' when DATA_PRECISION is not null and DATA_SCALE>0 then 'NUMBER('||DATA_PRECISION||','||DATA_SCALE||')' when DATA_TYPE<>'DATE' then DATA_TYPE||'('||DATA_LENGTH||')' else DATA_TYPE end as DATA_TYPE_, b.NULLABLE, b.DATA_LENGTH, b.DEFAULT_LENGTH, b.DATA_DEFAULT, DATA_PRECISION, DATA_SCALE, b.COLUMN_ID, b.DATA_TYPE FROM user_col_comments a LEFT JOIN user_tab_columns b ON a.table_name = b.table_name AND a.COLUMN_NAME = b.COLUMN_NAME WHERE a.table_name = 'OA_VEHICLE_OIL_CHARGE' ORDER BY b.COLUMN_ID ASC ``` + 修改表备注 ``` # 表备注 Comment on table DW_RE_PROGRESS_DETAIL is '项目进度-进度明细'; # 字段备注 comment on column Student.id is '学生id'; comment on column Student.name is '学生姓名'; ``` ## 1.3 视图 + 查询当前用户所有视图 ```sql select * from user_tab_comments where table_type='VIEW' ``` + 视图创建语句 ```sql select text from all_views where view_name='DW_SAFETY_RISK_LARG_QS_VW' ``` # 二、常用函数 ## 2.1 行转列、列转行 + pivot ```sql --行转列 select * from SalesList pivot( max(salesNum) for shangPin in ( --shangPin 即要转成列的字段 '上衣' as 上衣, --max(salesNum) 此处必须为聚合函数, '裤子' as 裤子, --in () 对要转成列的每一个值指定一个列名 '袜子' as 袜子, '帽子' as 帽子 ) ) where 1 = 1; --这里可以写查询条件,没有可以直接不要where ``` ```sql with hsb_stat as (select count(1) as num,'已完成重大污染物识别与评价项目' as item from SU_CHECK_ENVWATER_IMPL where STAT_ITEM_ID=110 and FINISH_STATUS=1 and PROJECT_ID=#{project_id} union select count(1) as num,'已完成环水保检测项目' as item from SU_CHECK_ENVWATER_IMPL where STAT_ITEM_ID=111 and FINISH_STATUS=1 and PROJECT_ID=#{project_id} union select count(1) as num,'已完成“三同时”落实情况项目' as item from SU_CHECK_ENVWATER_IMPL where STAT_ITEM_ID=112 and FINISH_STATUS=1 and PROJECT_ID=#{project_id} union select count(1) as num,'已完成环水保验收项目' as item from SU_CHECK_ENVWATER_IMPL where STAT_ITEM_ID=113 and FINISH_STATUS=1 and PROJECT_ID=#{project_id} union select nvl(sum(CHECK_COUNT),0) as num,'检查次数' as item from SU_CHECK_ENVWATER_IMPL where PROJECT_ID=#{project_id} union select nvl(sum(CHECK_ISSUE_COUNT),0) as num,'发现问题数' as item from SU_CHECK_ENVWATER_IMPL where PROJECT_ID=#{project_id} union select nvl(sum(RECTIFY_ISSUE_COUNT),0) as num,'整改完成' as item from SU_CHECK_ENVWATER_IMPL where PROJECT_ID=#{project_id}) -- 重点 select * from hsb_stat pivot(max(num) for item in ( '已完成“三同时”落实情况项目' as santongshi, '已完成环水保检测项目' as hsjc, '已完成环水保验收项目' as hsys, '已完成重大污染物识别与评价项目' as zdwrw, '检查次数' as jccs, '整改完成' as zgwc, '发现问题数' as fxwts )) ``` + merge into 合并 ```sql MERGE INTO t1 USING (SELECT id,name FROM t2) t2 ON ( t1.id=t2.id) WHEN MATCHED THEN UPDATE SET T1.name= t2.name WHEN NOT MATCHED THEN INSERT (id,name) VALUES (t2.id,t2.name); # 结合with MERGE INTO #TEMP1 A USING ( WITH SUMORDER AS (SELECT PRODUCTID, SUM(AMOUNT) TOTAL FROM ORDER GROUP BY PRODUCTID) SELECT * FROM SUMORDER ) B ON (A.PRODUCTID = B.PRODUCTID) WHEN MATCHED THEN UPDATE SET A.TOTAL = B.TOTAL; ``` ## 2.2 日期时间 + 数据库最大的年月往前推12个月 ```sql SELECT TO_CHAR( ADD_MONTHS( TO_DATE( to_char( to_date( ( select max(DECLARE_PERIOD_YEAR_MONTH) from CRZ_NMG_WORKER_WAGE_BOND where project_id=600000000000000138 ), 'yyyy-MM' ), 'yyyy-MM' ), 'yyyy-MM' ), ROWNUM - 12 ), 'yyyy-MM' ) AS MONTHLIST FROM DUAL CONNECT BY ROWNUM <= 12 ``` + 指定月份的前N个月 ```sql -- 获取2020-06的后5个月(2020-11) SELECT TO_CHAR(ADD_MONTHS(to_date('2020-06','yyyy-MM'),5),'YYYY-MM') FROM dual; -- 获取2020-06的前3个月(2020-03) SELECT TO_CHAR(ADD_MONTHS(to_date('2020-06','yyyy-MM'),-3),'YYYY-MM') FROM dual; ``` + 返回指定日期当月的最后一天 ```sql SELECT SYSDATE,last_day(SYSDATE) FROM dual; ``` ## 2.3 窗口函数 + over() ``` # 累加 sum(COLLECT_BOND_AMOUNT) over ( ORDER BY DECLARE_PERIOD_YEAR_MONTH desc) # 分组累加 sum( DESIGN_AMOUNT ) over ( partition BY PROJECT_ID order by DESIGN_AMOUNT desc) # 在按部门划分的基础上,工资从高到低分级,级别RANK从1开始依次递增 RANK() OVER(PARTITION BY E.DEPTNO ORDER BY E.SAL DESC) RANK # 记录后第N条 LEAD(E.SAL, 1, 0) OVER(PARTITION BY E.DEPTNO ORDER BY E.SAL) LEAD_SAL # 记录前面第N行记录 LAG(E.SAL, 1, 0) OVER(PARTITION BY E.DEPTNO ORDER BY E.SAL) LAG_SAL # 取行号 ROW_NUMBER() OVER(PARTITION BY E.DEPTNO ORDER BY E.SAL) ROW_NUM # 统计某组中的总计值 SUM(E.SAL) OVER(PARTITION BY E.DEPTNO) SUM_SAL # 统计某组中的平均值 AVG(E.SAL) OVER(PARTITION BY E.DEPTNO) AVG_SAL # 按某列分组,并统计该组中记录数量 COUNT(E.SAL) OVER(PARTITION BY E.DEPTNO) COUNT_SAL ``` ## 2.4 自定义函数 + md5 ``` CREATE OR REPLACE FUNCTION MD5( passwd IN VARCHAR2) RETURN VARCHAR2 IS retval varchar2(32); BEGIN retval := utl_raw.cast_to_raw(DBMS_OBFUSCATION_TOOLKIT.MD5(INPUT_STRING => passwd)); RETURN retval; END; select md5(123231132) from dual; ``` ## 2.5 递归 ```sql SELECT ID,SUPER_ID,NAME_,CODE, sys_connect_by_path(NAME_,'->') namepath, LEVEL FROM IDM_ENUM_CATEGORY START WITH NAME_='云南省' CONNECT BY PRIOR ID=SUPER_ID ``` ## 2.6 对象信息已锁定 ```sql -- 查询被锁表 SELECT owner,table_name,stattype_locked FROM DBA_TAB_STATISTICS a WHERE a.stattype_locked IN ('ALL','DATA','CACHE'); -- 解锁 EXEC dbms_stats.unlock_table_stats(ownname => 'JTT_CRM',tabname => 'SECTION_DETAIL_USER'); -- 生成结果存储过程(双引号换成单引号) select 'exec dbms_stats.unlock_table_stats("'||user||'","'||table_name||'");' from user_tab_statistics where stattype_locked IN ('ALL','DATA','CACHE'); ``` ## 2.7 创建唯一索引 ```sql create unique index gd_person_edu_uniq on GD_PERSON_EDU(PERSON_ID,EDU_,EDU_CODE,EDU_TYPE,EDU_TYPE_CODE); ``` ## 2.8 查询表约束 ```sql -- 查询约束 select * from user_constraints where table_name='EA_DIVISION_CATEGORY_INFO' -- 删除约束 alter table EA_DIVISION_CATEGORY_INFO drop constraints SYS_C00682807 ``` ## 2.9 查询锁表 ```sql select object_name, machine, s.sid, s.serial# from v$locked_object l, dba_objects o, v$session s where l.object_id  =  o.object_id and l.session_id = s.sid; ----- 删除锁 alter system kill session 'SID,serial#'; alter system kill session '909,10021'; ``` ## 2.10 查看执行历史 ```sql -- 根据表名查询执行历史 select * from v$sqlarea a where a.SQL_TEXT like '%JTXY_CREDIT_RECORDS%' order by a.LAST_ACTIVE_TIME desc; ``` ## 2.11 从日期获取年、月 ```sql -- 取年 to_number(to_char(a.SUPPLY_DATE,'yyyy')) -- 取月 to_number(to_char(a.SUPPLY_DATE,'MM')) ``` ## 2.12 列转行 ```sql -- listagg select listagg(b.name_,',') within GROUP (ORDER BY b.name_) as secNames from WZ_SUPPLY_CONTRACT a left join BASE_IDM_PRO_ORG b on a.SECTION_ID=b.ORG_ID where a.SFID_=#{sfId} ``` ## 2.13 case when ```sql case b.REGIST_TYPE when 'constructionUnit' then '施工' when 'supervisionUnit' then '监理' when 'designUnit' then '设计' when 'detectionUnit' then '勘查' end as REGIST_TYPE, ```