实时获得最耗CPU资源的SQL语句(zt)

本文介绍如何通过Shell脚本实时捕捉Oracle数据库中CPU消耗最高的SQL语句。包括两个脚本:get_by_spid.sh用于根据SPID获取SQL语句;topsql.sh则循环调用前者以获取系统中CPU使用率最高的Oracle进程正在执行的SQL。
Oracle 性能诊断和日常监控中,最耗CPU的语句通常也是我们最需要关心的语句。所以在Oracle10g的awr中,将cpu time和elapsed time最高的语句加入到了报表,并且放到了 SQL 语句部分的前两位。那么在平时的监控中,也可以通过 shell 脚本实时捕获系统中CPU耗用最多的进程中正在执行的SQL,以更加有效和及时的诊断和发现问题。[@more@]

首先写一个根据spid来或者其SQL的脚本get_by_spid.sql

#!/bin/ksh
# creator:NinGoo
# function: get sql statement by spid
# parameter: spid
# useage: get_by_spid.sh spid

sqlplus -S /nolog < connect / as sysdba;
col SERIAL# format 999999
col sid format 99999
col username format a10
col machine format a12
col program format a32
col sql_text format a81
set lines 1000
set pages 1000
set verify off
col sql_hash_value new_value hash_value head hash_value
select sid,serial#,username,program,sql_hash_value,
to_char(logon_time,'yyyy/mm/dd hh24:mi:ss') as login_time
from v$session
where paddr in ( select addr from v$process where spid=$1);

select sql_text
from v$sqltext_with_newlines
where hash_value = &hash_value
order by piece;
exit;
EOF

然后再在另外一个shell脚本topsql.sh中获得系统中CPU耗用最多的oracle server process的spid,循环调用第一个脚本获得SQL

#!/bin/ksh
# creator:NinGoo
# function: get top cpu sql
# parameter: N
# useage: topsql.sh N

if [ $# -eq 0 ]; then
echo "Usage: `basename $0` N"
exit 1
fi

topcpu=`ps auxw|grep LOCAL|sort -rn +2 |head -$1|awk '{print $2}'`
i=0

for spid in $topcpu
do
i=`expr $i + 1`
echo "33[32;1m===============top $i cpu sql=============33[0m"
. /home/oracle/worksh/get_by_spid.sh $spid
done

那么调用就很简单了,假如我们要看系统top 3的sql语句,只需要执行topsql.sh 3即可。当然,如果我们自己通过top/topas等工具已经获得spid了,那么只要执行get_by_spid.sh spid就能获得该进程正在执行的sql语句了。

--&gt

--EOF--

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/35489/viewspace-1002594/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/35489/viewspace-1002594/

# -*- coding: utf-8 -*- """ @file: zt_fsmorder @author: zhangxiukun @date: 2025/7/17 15:23 """ from tortoise import run_async from app.models.change import ChangeLedger from app.settings import TORTOISE_ORM from app.utils.db import MySqlClient # # 示例用法 async def get_zt_dept(sql: str = 'select * from zt_dept'): result = {} async with MySqlClient(TORTOISE_ORM) as client: for item in await client.execute_query(sql): result[item['id']] = item.get('name', '') print(result) return result async def get_zt_user(sql: str = 'select * from zt_user'): result = {} async with MySqlClient(TORTOISE_ORM) as client: for item in await client.execute_query(sql): result[item['account']] = item.get('realname') return result async def get_zt_equip(sql: str = 'select * from zt_equip'): result = {} async with MySqlClient(TORTOISE_ORM) as client: for item in await client.execute_query(sql): result[item['id']] = item.get('name') return result async def get_zt_hwswco(sqlfile: str = './sql/zt_hwswco.sql'): user_dict = await get_zt_user() dept_dict = await get_zt_dept() result = [] with open(sqlfile, 'r', encoding='utf-8') as f: sql = f.read() async with MySqlClient(TORTOISE_ORM) as client: for item in await client.execute_query(sql): # dept=item.get('dept','') # dept_name = dept_dict.get(int(dept), '') # item['dept'] = dept_name regional_head = item.get('regional_head', '') regional_head_name = user_dict.get(regional_head, '') elec_responsible_person = item.get('elec_responsible_person', '') elec_responsible_person_name = user_dict.get(elec_responsible_person, '') soft_responsible_person = item.get('soft_responsible_person', '') soft_responsible_person_name = user_dict.get(soft_responsible_person, '') item['elec_responsible_person_name'] = elec_responsible_person_name item['soft_responsible_person_name'] = soft_responsible_person_name result.append(item) print(result) return result async def insert_hwswco_info(): for data in await get_zt_hwswco(): print(data) id = data['hwswco_id'] await ChangeLedger.update_or_create(hwswco_id=id, defaults=data) if __name__ == "__main__": run_async(insert_hwswco_info()) 按照这种形式完成代码
08-22
class ZtSdBookDetailRf(BaseModel, TimestampMixin): id = fields.IntField(pk=True, description="主键ID") zt_id = fields.IntField(pk=False, description='禅道主键') project_no = fields.CharField(max_length=50, description="项目号") software_category = fields.CharField(max_length=50, default='', description="软件类别") software_item_umber = fields.CharField(max_length=50, null=True, description="软件物料号") baseline_name = fields.CharField(max_length=255, default='', description="软件物料名称") work_order_no = fields.CharField(max_length=50, description="工单号") upgrade_status = fields.CharField(max_length=50, null=True, description="升级状态") upgrade_date = fields.DateField(null=True, description="升级完成时间") upgrader = fields.CharField(max_length=30, null=True, description="升级人") first_licensed_date = fields.DateField(null=True, description="首次授权到期日") class Meta: table = "zt_sdbookdetailrf" table_description = "台账明细表" default_connection = "default" 这是model的定义,是新表的结构,修改下面的代码 # -*- coding: utf-8 -*- """ @file: async_zt_flow_hcproblem @author: zhangxiukun @date: 2025/7/17 10:14 """ from tortoise import run_async from app.models.zentao import ZtSdBookDetailRf from app.settings import TORTOISE_ORM from app.utils.db import MySqlClient async def get_processed_standingbookdetail(): """ 读取zt_standingbookdetail表数据并生成转换记录 """ processed_data = [] sql = "SELECT * FROM zt_standingbookdetail" async with MySqlClient(TORTOISE_ORM) as client: rows = await client.execute_query(sql) for row in rows: # 创建更新后的记录 new_row = dict(row) new_row['configname'] = new_row['baselinename'] # 生成upperconfig记录 upper_record = new_row.copy() upper_record['softwarecategory'] = 'upperconfig' # 生成lowerconfig记录 lower_record = new_row.copy() lower_record['softwarecategory'] = 'lowerconfig' processed_data.append(upper_record) processed_data.append(lower_record) return processed_data async def insert_processed_data(): """ 将转换后的数据插入到新表 """ # 获取处理后的数据 data = await get_processed_standingbookdetail() # 插入SQL语句 insert_sql = """ INSERT INTO zt_standingbookdetail_new ( projectno, softwarecategory, softwareitemnumber, baselinename, confignumber, configname, workorderno, upgradestatus, upgradedate, upgrader, pcbox, card, cpu, memory, disk, firstlicenseddate ) VALUES ( %(projectno)s, %(softwarecategory)s, %(softwareitemnumber)s, %(baselinename)s, %(confignumber)s, %(configname)s, %(workorderno)s, %(upgradestatus)s, %(upgradedate)s, %(upgrader)s, %(pcbox)s, %(card)s, %(cpu)s, %(memory)s, %(disk)s, %(firstlicenseddate)s ) """ async with MySqlClient(TORTOISE_ORM) as client: # 分批次插入(每1000条一批) batch_size = 1000 total_inserted = 0 for i in range(0, len(data), batch_size): batch = data[i:i + batch_size] # 使用事务保证数据一致性 try: await client.start_transaction() for record in batch: await client.execute_query(insert_sql, record) await client.commit_transaction() total_inserted += len(batch) except Exception as e: await client.rollback_transaction() raise e print(f"成功插入 {total_inserted} 条记录到 zt_standingbookdetail_new 表中。") if __name__ == "__main__": run_async(insert_processed_data()) if __name__ == '__main__': run_async(insert_zt_standingbookdetail())
08-22
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值