gpt4 book ai didi

PostgreSQL 函数/存储过程 CURRENT_TIMESTAMP 不改变

转载 作者:行者123 更新时间:2023-11-29 11:59:52 25 4
gpt4 key购买 nike

我想跟踪函数内的执行时间。例如,我有以下状态跟踪表:

    CREATE TABLE status_table
(
run_id numeric NOT NULL,
start_ts timestamp(6) without time zone NOT NULL,
end_ts timestamp(6) without time zone NOT NULL
)
WITH (
OIDS=FALSE
)
DISTRIBUTED RANDOMLY;

我有以下示例函数,它使用 PG_SLEEP(5) 作为我的函数实际执行的模拟:

CREATE OR REPLACE FUNCTION wrapper_func(p_run_id numeric)
RETURNS numeric AS
$BODY$
Declare
tmp_start_ts timestamp(6) without time zone;
tmp_end_ts timestamp(6) without time zone;

BEGIN
tmp_start_ts := CURRENT_TIMESTAMP;
PERFORM PG_SLEEP(5);
tmp_end_ts := CURRENT_TIMESTAMP;
INSERT INTO status_table (run_id,start_ts,end_ts) VALUES (p_run_id,tmp_start_ts,tmp_end_ts);
RETURN 0;
END;
$BODY$
LANGUAGE plpgsql VOLATILE;

然后我调用了这个函数三次,每次调用之间等待大约 20 秒:

SELECT * FROM wrapper_func(1);
SELECT * FROM wrapper_func(2);
SELECT * FROM wrapper_func(3);

但是,当我查看 status_table 中的结果时,时间戳都是相同的:

SELECT * FROM status_table ORDER BY run_id;

run_id|start_ts|end_ts
1|2015-01-18 17:54:43.641294|2015-01-18 17:54:43.641294
2|2015-01-18 17:54:43.641294|2015-01-18 17:54:43.641294
3|2015-01-18 17:54:43.641294|2015-01-18 17:54:43.641294

有人可以指出我做错了什么或另一种方法来完成这个吗?

谢谢

最佳答案

在您的函数中使用 clock_timestamp() 而不是 CURRENT_TIMESTAMP

CURRENT_TIMESTAMP 将根据当前事务的开始时间返回值。

参见 document

关于PostgreSQL 函数/存储过程 CURRENT_TIMESTAMP 不改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28015914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com