Oracle PL/SQL更新程序运行时长计算出现异常数值问题
正确计算Oracle PL/SQL更新程序运行时长的方法
你遇到的奇怪负数是两个问题导致的:
- 计算顺序反了:
startDate - endDate得到的是负数(endDate在操作结束后赋值,时间晚于startDate) - DATE类型相减的结果是天数,那个小数是一天的几分之几(比如0.000011574≈1秒,因为1天=86400秒)
另外你原代码里有个语法错误:my_record.my_Table%rowtype; 应该改成 my_record my_Table%rowtype;(把点号换成空格)。
下面是几种靠谱的计算方式:
方法1:修正DATE计算逻辑并格式化输出
直接调整相减顺序,再把天数转换为更易读的秒数或时分秒格式:
declare cursor c1 is select * from my_Table; my_record my_Table%rowtype; startDate DATE; endDate DATE; elapsed_seconds NUMBER; begin startDate := SYSDATE; -- 无需查询dual,直接赋值更高效 open c1; loop fetch c1 into my_record; exit when c1%notfound; -- 你的更新逻辑 end loop; -- commit; close c1; endDate := SYSDATE; -- 输出耗时天数 DBMS_OUTPUT.PUT_LINE('耗时(天):' || (endDate - startDate)); -- 转换为秒数输出 elapsed_seconds := (endDate - startDate) * 86400; DBMS_OUTPUT.PUT_LINE('耗时(秒):' || elapsed_seconds); -- 格式化为时分秒输出 DBMS_OUTPUT.PUT_LINE('耗时:' || TO_CHAR(TRUNC(elapsed_seconds)/3600, 'FM999') || '小时 ' || TO_CHAR(MOD(TRUNC(elapsed_seconds), 3600)/60, 'FM999') || '分钟 ' || TO_CHAR(MOD(elapsed_seconds, 60), 'FM999.999') || '秒'); end; /
方法2:用TIMESTAMP获取微秒级精度
如果你的程序运行时间很短,需要更精确的统计,可以用TIMESTAMP类型(精度到微秒):
declare cursor c1 is select * from my_Table; my_record my_Table%rowtype; start_ts TIMESTAMP; end_ts TIMESTAMP; elapsed interval day(9) to second(6); begin start_ts := SYSTIMESTAMP; open c1; loop fetch c1 into my_record; exit when c1%notfound; -- 你的更新逻辑 end loop; -- commit; close c1; end_ts := SYSTIMESTAMP; elapsed := end_ts - start_ts; DBMS_OUTPUT.PUT_LINE('耗时:' || elapsed); end; /
运行后会直接输出类似 +00 00:00:01.123456 的格式,包含微秒信息。
方法3:使用DBMS_UTILITY.GET_TIME函数
这个函数返回当前时间的百分之一秒数,差值计算更直观:
declare cursor c1 is select * from my_Table; my_record my_Table%rowtype; start_time NUMBER; end_time NUMBER; elapsed_seconds NUMBER; begin start_time := DBMS_UTILITY.GET_TIME; open c1; loop fetch c1 into my_record; exit when c1%notfound; -- 你的更新逻辑 end loop; -- commit; close c1; end_time := DBMS_UTILITY.GET_TIME; elapsed_seconds := (end_time - start_time)/100; DBMS_OUTPUT.PUT_LINE('耗时(秒):' || elapsed_seconds); end; /
内容的提问来源于stack exchange,提问作者4est
相关产品推荐
相关产品推荐

