当前位置: 首页 > 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

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • AI时代,我们还可以做什么?
  • android系统中data下的xml乱码无法查看问题剖析及解决方法
  • C++ 11 for 循环和容器
  • Linux安全与高级应用(七)深入Linux Shell脚本编程:循环与分支结构的高级应用
  • 【算法】装箱问题
  • Apache Kylin分布式的分析数据仓库
  • pdf怎么加密码怎么设置密码?pdf加密码的几种设置方法
  • Python的安装环境以及应用
  • 日撸Java三百行(day17:链队列)
  • Adobe Premiere Pro 2024 v24.5.0.057 最新免费修改版
  • Flink Maven 依赖
  • gorm入门——如何实现分页查询
  • LVS(Linux virual server)详解
  • 密码学基础-为什么使用真随机数(True Random Number Generators)
  • 【Git】Git安装_配置
  • 【Leetcode】104. 二叉树的最大深度
  • 2018一半小结一波
  • avalon2.2的VM生成过程
  • cookie和session
  • GitUp, 你不可错过的秀外慧中的git工具
  • leetcode388. Longest Absolute File Path
  • Node + FFmpeg 实现Canvas动画导出视频
  • October CMS - 快速入门 9 Images And Galleries
  • OpenStack安装流程(juno版)- 添加网络服务(neutron)- controller节点
  • React Transition Group -- Transition 组件
  • Storybook 5.0正式发布:有史以来变化最大的版本\n
  • vue2.0开发聊天程序(四) 完整体验一次Vue开发(下)
  • 测试如何在敏捷团队中工作?
  • 前端技术周刊 2019-01-14:客户端存储
  • 让你成为前端,后端或全栈开发程序员的进阶指南,一门学到老的技术
  • 如何优雅地使用 Sublime Text
  • 这几个编码小技巧将令你 PHP 代码更加简洁
  • Semaphore
  • ​DB-Engines 11月数据库排名:PostgreSQL坐稳同期涨幅榜冠军宝座
  • #includecmath
  • #职场发展#其他
  • $$$$GB2312-80区位编码表$$$$
  • (2)nginx 安装、启停
  • (C++二叉树05) 合并二叉树 二叉搜索树中的搜索 验证二叉搜索树
  • (delphi11最新学习资料) Object Pascal 学习笔记---第7章第3节(封装和窗体)
  • (vue)el-tabs选中最后一项后更新数据后无法展开
  • (第30天)二叉树阶段总结
  • (三)Honghu Cloud云架构一定时调度平台
  • (原創) 如何使用ISO C++讀寫BMP圖檔? (C/C++) (Image Processing)
  • .NET 4 并行(多核)“.NET研究”编程系列之二 从Task开始
  • .Net Remoting(分离服务程序实现) - Part.3
  • .NET/C# 编译期能确定的字符串会在字符串暂存池中不会被 GC 垃圾回收掉
  • .NET/C# 在代码中测量代码执行耗时的建议(比较系统性能计数器和系统时间)
  • .NET分布式缓存Memcached从入门到实战
  • /bin、/sbin、/usr/bin、/usr/sbin
  • @antv/x6 利用interacting方法来设置禁止结点移动的方法实现。
  • @SpringBootConfiguration重复加载报错
  • [ 隧道技术 ] 反弹shell的集中常见方式(四)python反弹shell
  • [2016.7 Day.4] T1 游戏 [正解:二分图 偏解:奇葩贪心+模拟?(不知如何称呼不过居然比std还快)]
  • [2019红帽杯]Snake