当前位置: 首页 > news >正文

Oracle DBA常用 sql

文章目录

    • 一、基础环境
    • 二、常用 sql
    • 三、参考资料

  版权声明:本文为CSDN博主「杨群」的原创文章,遵循 CC 4.0 BY-SA版权协议,于2023年7月6日首发于CSDN,转载请附上原文出处链接及本声明。
  原文链接:https://blog.csdn.net/u011046671/article/details/140909535

一、基础环境

  操作系统:Windows 或 Linux
  数据库版本:Oracle Database 11.2.0.1.0 及以上版本

二、常用 sql

  • 以操作系统验证的方式登录到数据库(sys),无需密码。需要在数据库服务器本地执行

    sqlplus / as sysdba
    
  • 将数据库注册到监听

    alter system register;
    
  • 查询实例信息

    set pagesize 100;
    set linesize 200;
    col instance_number format 9;
    col instance_name format a15;
    col host_name format a10;
    col version format a10;
    col startup_time format a20;
    col status format a6;
    select t.instance_number,t.instance_name,t.host_name,t.version,t.startup_time,t.status from v$instance t;
    
  • 查询正在进行中的事务,需要使用DBA权限用户执行

    select a.sid,a.serial#,a.username,b.start_scn,b.used_ublk,b.used_urec,b.start_timefrom v$session a, v$transaction bwhere a.saddr = b.ses_addr;
    

    这个查询将返回正在运行的事务的相关信息,包括会话ID(SID)、序列号(SERIAL#)、用户名(USERNAME)、
    事务开始的SCN(START_SCN)、使用的UNDO块数(USED_UBLK)、使用的回滚段记录数(USED_UREC)以及事务开始的时间(START_TIME)。

  • 统计数据表空间使用率

    set pagesize 100;
    set linesize 200;
    select a.tablespace_name "表空间名",total / (1024 * 1024) "表空间大小(MB)",free / (1024 * 1024) "表空间剩余大小(MB)",(total - free) / (1024 * 1024) "表空间使用大小(MB)",round((total - free) / total, 4) * 100 "使用率 %"from (select tablespace_name, sum(bytes) freefrom dba_free_spacegroup by tablespace_name) a,(select tablespace_name, sum(bytes) totalfrom dba_data_filesgroup by tablespace_name) bwhere a.tablespace_name = b.tablespace_name
    order by a.tablespace_name;
    
  • 统计临时表空间使用率

    select d.tablespace_name,space "SUM_SPACE(M)",blocks sum_blocks,used_space "USED_SPACE(M)",round(nvl(used_space, 0) / space * 100, 2) "USED_RATE(%)",nvl(free_space, 0) "FREE_SPACE(M)"from (select tablespace_name,round(sum(bytes) / (1024 * 1024), 2) space,sum(blocks) blocksfrom dba_temp_filesgroup by tablespace_name) d,(select tablespace_name,round(sum(bytes_used) / (1024 * 1024), 2) used_space,round(sum(bytes_free) / (1024 * 1024), 2) free_spacefrom v$temp_space_headergroup by tablespace_name) fwhere d.tablespace_name = f.tablespace_name(+);
    
  • 看表空间是否自动扩展

    select t.file_id, t.tablespace_name, t.file_name, t.autoextensiblefrom dba_data_files torder by 1;
    
  • 手动扩展数据表空间

    alter database datafile '普通数据文件绝对路径' resize 1024m;
    
  • 手动扩展临时表空间

    alter database tempfile '临时数据文件绝对路径' resize 1024m;
    
  • 通过增加数据文件的方式扩展表空间(如果能够自动扩展就不必手动扩展)

    alter tablespace [表空间名称]
    add datafile '数据文件绝对路径'
    size 64m 
    autoextend on next 64m 
    maxsize unlimited logging
    extent management local autoallocate
    segment space management auto;
    
  • 缩小临时表空间,将执行结果再次执行。

    select 'alter tablespace '||tablespace_name ||' shrink space ;' from dba_temp_files;
    
  • 询数据库信息(是否开启归档模式)

        select t.name          "实例名",t.created       "创建时间",t.log_mode      "日志模式",t.open_mode     "开启模式",t.platform_name "平台名称"from v$database t;
    
  • 将数据库重启至 mount 状态

    shutdown immediate ;
    startup mount ;
    
  • 修改实例的归档模式为 archivelog

    alter database archivelog ;
    
  • 修改归档日志空间大小为200GB(默认为4GB)。

    alter system set db_recovery_file_dest_size = 204800M ;
    
  • 打开数据库

    alter database open ;  
    
  • 查看归档日志大小及使用情况

    col name format a41;
    select t.name,t.space_limit / 1024 / 1024 "space_limit(M)",t.space_used / 1024 / 1024 "space_used(M)",t.space_reclaimable / 1024 / 1024 "space_reclaimable(M)",t.number_of_filesfrom v$recovery_file_dest t;
    
  • 询归档空间使用百分比。如果 ARCHIVED LOG 超过 90% oracle 随时有宕机的危险。

        col file_type format a20;col percent_space_used format 9999;col percent_space_reclaimable format 9999;col number_of_files format 9999;select t.file_type,t.percent_space_used        "空间使用百分比",t.percent_space_reclaimable "可回收空间百分比",t.number_of_files           "文件个数"from v$flash_recovery_area_usage twhere t.file_type = 'ARCHIVED LOG';
    
  • 清理归档日志

    -- 连接本地数据库的恢复管理器(使用操作系统用户认证)
    rman target /
    -- 检查文件清单
    crosscheck archivelog all;
    -- 删除今天之前的日志
    delete archivelog until time 'sysdate';
    
  • 查询回收站状态

    show parameter recyclebin;
    
  • 关闭回收站,需要重启数据库后生效

    alter system set recyclebin=off scope=spfile;
    
  • 清空用户自己的回收站

    purge recyclebin;
    
  • 清空dba回收站(sys身份执行)

    purge dba_recyclebin;
    
  • 清空审计表(必须用 sysdba 身份)

    truncate table sys.aud$;
    
  • 创建表时强制分配segment,防止空表无法使用exp导出

    alter system set deferred_segment_creation = false;
    
  • 查询修改结果

    show parameter deferred_segment_creation;
    
  • 密码设置永不过期(不建议使用)

    alter profile default limit password_life_time unlimited;
    
  • 锁定不使用的用户

    alter user [用户名] account lock ;
    
  • 关闭数据库的监听日志功能,防止日志达到4GB后监听失效

    lsnrctl set log_status off
    lsnrctl save_config
    echo 重启监听使修改生效
    lsnrctl stop
    lsnrctl start
    
  • sqlplus 全局永久配置

    -- 服务器路径:%ORACLE_HOME%\sqlplus\admin\glogin.sql
    -- 设置每页显示的行数
    set pagesize 100;
    -- 设置每行显示的宽度
    set linesize 200;
    -- 格式化当前会话日期格式
    alter session set nls_date_format='yyyy-mm-dd hh24:mi:ss';
    
  • 查询用户清单

    col username format a20;
    col user_id format 9999;
    col account_status format a20;
    col lock_date format a20;
    col expiry_date format a20;
    col default_tablespace format a20;
    col temporary_tablespace format a20;
    select u.username,u.user_id,u.account_status,u.lock_date,u.expiry_date,u.default_tablespace,u.temporary_tablespacefrom dba_users uorder by 2;
    
  • 删除用户,包含用户的对象

    drop user [帐号] cascade;
    
  • 修改密码

    alter user [帐号] identified by [密码];
    
  • 修改 system 密码

    alter user system identified by Oracle#2024;
    
  • 用户解锁

      alter user [帐号] account unlock;
    
  • 用户批量解锁,将查询结果再次执行

    select 'alter user ' || lower(username) || ' account unlock; 'from dba_users t -- where 条件order by username;
    
  • 创建用户

    create user [帐号]
    identified by [密码]
    default tablespace [默认表空间]
    quota unlimited on [默认表空间]
    temporary tablespace temp;
    
  • 授予连接权限和资源使用权限

    grant connect,resource to [帐号];
    
  • 授予DBA权限

    grant dba to [帐号];
    
  • 收回dba权限

    revoke dba from [帐号];
    
  • 查询数据文件清单

    col file_id format 9999;
    col file_name format a60;
    col tablespace_name format a20;
    select file_id, file_name, tablespace_name from dba_data_files order by 1;
    
  • 查询数据库字符集

    select userenv('language') from dual;col parameter format a20;
    col value format a50;
    select parameter, value from v$nls_parameters;
    
  • 查询用户的作业

    select t.job, t.what, t.last_date, t.next_date, t.intervalfrom user_jobs torder by 1;
    
  • 删除作业

    begindbms_job.remove(job_id);commit;
    end;
    /
    
  • 查看补丁安装状态

    col action_time format a22;
    col action format a6;
    col namespace format a10;
    col version format a24;
    col id format 99999999;
    col bundle_series format a6;
    col comments format a26;
    select t.action_time, t.action,  t.namespace, t.version, t.id, t.bundle_series, t.commentsfrom dba_registry_history t;
    
  • 修改用户默认的表空间

    alter user [账号] default tablespace [表空间名称]; 
    
  • 关闭数据库审计功能(不建议使用)

    alter system set audit_trail=none scope=spfile;
    
  • 检查 Oracle 数据库勒索病毒 RushQL(服务器端),预期结果:以下3个语句查询结果为空

    select *from all_procedureswhere procedure_name in ('DBMS_SUPPORT_INTERNAL','DBMS_STANDARD_FUN9','DBMS_SYSTEM_INTERNA','DBMS_CORE_INTERNAL');  			
    select * from all_triggers where trigger_name like '%DBMS%';
    select *from all_triggerswhere trigger_name in ('DBMS_SUPPORT_INTERNAL','DBMS_SYSTEM_INTERNAL','DBMS_CORE_INTERNAL');
    
  • 删除表空间(包含数据文件)

    drop tablespace [表空间名称] including contents and datafiles;
    
  • 删除空的数据文件(包含数据文件)

    alter tablespace [表空间名称] drop datafile [数据文件绝对路径];
    
  • 查询当前用户所有的分区表信息

    select t.table_name,t.partition_position,t.partition_name,t.num_rowsfrom user_tab_partitions t;
    
  • 增加25年1月分区

    alter table emp add partition p2501 values less than (to_date('202502', 'yyyymm'));
    
  • 删除分区

    alter table [表名] drop partition [分区名称];
    
  • 清空分区

    alter table [表名] truncate partition p2101;
    
  • 查询某个分区数据

    select empno, ename, hiredate from emp partition (p2101);
    
  • 修改字段长度

    alter table 表名 modify 字段名 varchar2(10);
    
  • 增加字段

    alter table [表名] add [字段名] [字段类型];
    
  • 手动收集某个表统计信息

        begindbms_stats.gather_table_stats(ownname => 'username',tabname => 'TABLENAME');end;
    
  • 手动收集某个用户所有表的统计信息

        begindbms_stats.gather_schema_stats(ownname          => '[用户名大写]',options          => 'GATHER',estimate_percent => dbms_stats.auto_sample_size,method_opt       => 'for all columns size skewonly',degree           => 7);end;/
    
  • 统计表注释,数据表名和数据条数

        col table_name format a30;col comments format a60;col num_rows format 99999;select a.table_name, b.comments, a.num_rows, a.last_analyzedfrom user_tables aleft join user_tab_comments bon a.table_name = b.table_namewhere a.temporary = 'N'order by a.num_rows desc nulls last;
    
  • 查询业务账户临时表

     select t.owner, t.table_name, t.statusfrom all_tables twhere temporary = 'Y'order 1;
    
  • 创建临时表空间

        create temporary tablespace cz_tdcrj_temptempfile '[数据文件绝对路径]' size 512m reuse autoextend on next  10mmaxsize unlimited;
    
  • 创建UNDO表空间

    create undo tablespace undotbs2
    datafile '/cais/oracle/oradata/symswap/UNDOTBS2.DBF'
    size 1024m
    reuse autoextend on;
    
  • 查询UNDO表空间的使用情况

    select tablespace_name, status, sum(bytes/1024/1024) "MB"
    from dba_undo_extents
    group by tablespace_name, status
    order by 1, 2;
    
  • 通过增加数据文件的方式扩展UNDO表空间

    alter tablespace UNDOTBS1
    add datafile 'D:\PROGRAMFILES\ORACLE\ORADATA\CSSJ\UNDOTBS02.DBF'
    size 1024m 
    autoextend on next 1024m 
    maxsize unlimited;
    
  • 修改用户的临时表空间为系统的临时表空间,通用生成语句,将生成结果执行

    select 'alter user '||username||' temporary tablespace temp;' from dba_users where username like 'DB%';
    
  • 修改用户的默认表空间为指定表空间

    alter user [用户名] default tablespace [表空间名称];
    
  • 查询表空间上的对象,包括普通表、索引、大对象

    select owner         as owner,'table'       as segment_type,table_name    as segment_name
    from dba_tables 
    where tablespace_name=&tablespace_name
    union all
    select owner         as owner,'index'       as segment_type,index_name    as segmetn_name
    from dba_indexes 
    where tablespace_name=&tablespace_name
    union all
    select owner         as owner,'lobsegment'  as sgement_type,segment_name  as segment_name
    from dba_lobs 
    where tablespace_name=[表空间名称];
    
  • 查询用户所有索引。valid:有效

    select index_name,tablespace_name,table_type,status from user_indexes;
    
  • 重建指定索引

    select 'alter index ' || t.index_name || ' rebuild tablespace ' ||t.table_owner || '_DATA;'
    from user_indexes t
    where t.tablespace_name <> t.table_owner || '_DATA';
    
  • 查询索引编译失败的索引,使用system用户执行

    select t.owner, t.index_name, t.index_type, t.table_owner, t.table_name, t.tablespace_name, t.status
    from all_indexes t 
    where t.owner like 'CZ%' 
    and t.status ='UNUSABLE';
    
  • 批量重新编译索引的语句,使用system用户执行

    select 'alter index ' || t.owner || '.' || t.index_name ||' rebuild tablespace ' || t.owner || '_DATA;'
    from all_indexes t
    where t.owner like 'CZ%'
    and T.status = 'UNUSABLE';
    
  • 修改用户的属性文件

    alter user cz_fxbd profile default;
    
  • 将数据表从一个表空间迁移到另外一个表空间

    alter table t_app_srkb move tablespace cz_srfx_data
    
  • 查找出不是浮点数的字段值

     -- 正则表达式:^(-?\d+)(.\d+)?$ 用于匹配:浮点数(包含正负号、小数点、数字0-9)select column_name from table_name t where not regexp_like(column_name, '^(-?\d+)(.\d+)?$');
    
  • 把时间戳(文本格式)转换成date格式

    select to_date(to_char(cast(cast(字段名 as timestamp) as date), 'yyyy-mm-dd hh24:mi:ss'),'yyyy-mm-dd hh24:mi:ss')
    from 表名
    
  • 查询默认属性文件

    col resource_name format a25;
    col limit format a10;
    select t.resource_type, t.resource_name,t.limit from dba_profiles t where profile = 'DEFAULT';
    
  • 查询当前用户名非空的会话总数

    select count(*) from v$session where username is not null;
    
  • 查询当前用户名称及连接数

    select username,count(username) from 
    v$session
    where username is not null 
    group by username ;
    
  • 查询当前用户job总数

    select count(*) from user_jobs;
    
  • 存储过程异常处理DBMS输出

    dbms_output.put_line('错误代码:' || sqlcode);
    dbms_output.put_line('错误详情:' || sqlerrm);
    dbms_output.put_line('出错行号:' || dbms_utility.format_error_backtrace());
    rollback;
    
  • 批量重新编译存储过程,将查询结果执行

    select 'alter ' || object_type || ' ' || object_name || ' compile;'from user_objectswhere status = 'INVALID';
    
  • 重新编译单个存储过程

    alter procedure 存储过程名称 compile;
    
  • 存储过程中执行sql语句

    execute immediate v_sql;
    
  • 将存储过程执行结果存入变量中

    v_sql := 'select count(*) from tab';
    execute immediate v_sql into v_vnt;
    

    三、参考资料

  版权声明:本文为CSDN博主「杨群」的原创文章,遵循CC 4.0 BY-SA版权协议,于2023年7月6日首发于CSDN,转载请附上原文出处链接及本声明。
  原文链接:https://blog.csdn.net/u011046671/article/details/140909535

http://www.lryc.cn/news/417733.html

相关文章:

  • MindSearch:AI 时代的“思考型”搜索引擎
  • 机器学习练手(四):基于SVM 的肥胖风险分类
  • AutoGPT项目实操总结
  • uniapp 荣耀手机 没有检测到设备 运行到Android手机 真机运行
  • 【EtherCAT】Windows+Visual Studio配置SOEM主站——静态库配置+部署
  • 【Python小游戏示例:猜拳游戏】
  • 多态实现的必要条件,实现多态的三个方法,输入一个URL的过程,死锁产生的原理和条件,进程和线程的定义及区别,进程通信的几种方式
  • Springboot+MybatisPlus项目中,数据库表中存放Date,查出后转为String
  • JavaDS —— AVL树
  • NSSCTF练习记录:[SWPUCTF 2021 新生赛]jicao
  • LabVIEW位移检测系统
  • 02、MySQL-DML(数据操作语言)
  • vue3 项目部署到线上环境,初始进入系统,页面卡顿大概一分钟左右,本地正常无卡顿。localStorage缓存1MB数据导致页面卡顿。
  • 软件更新中的风险识别与质量保证机制分析
  • QT下载与安装
  • Java 2.2 - Java 集合
  • Linux驱动.之I2C,iic驱动层(二)
  • 【STM32】USART串口和I2C通信
  • 【Material-UI】按钮组:垂直按钮组详解
  • DDR5 的优势与应用
  • STM32 - 笔记
  • 基于QT实现的简易WPS(已开源)
  • Flask-WTF 表单处理详细教程(第六阶段)
  • C语言 | Leetcode C语言题解之第330题按要求补齐数组
  • 无人机之测绘行业篇
  • Java编程:每日挑战
  • 【自动驾驶】ubuntu server安装桌面版
  • 前端模块化-手写mini-vite
  • SpringBoot中fastjson扩展: 自定义序列化和反序列化方法实战
  • 【QT】鼠标按键事件 - QMouseEvent QKeyEvent