Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

plpgsql - PostgreSQL Function / Stored Procedure CURRENT_TIMESTAMP does not change

I want to track the execution time within a function. As an example, I have the following status tracking table:

    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;

I have the following example function that uses PG_SLEEP(5) as the simulation of what my function will actually do:

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;

I then called this function three times, waiting about 20 seconds between each invocation:

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

However, when I look at the results in my status_table, the timestamps are all the same:

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

Could someone point out what I'm doing wrong or another approach to accomplish this?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

use clock_timestamp() instead of CURRENT_TIMESTAMP in your function

CURRENT_TIMESTAMP will return values based on the start time of the current transaction.

see document


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...