gpt4 book ai didi

sql - postgreSQL中执行查询的时间

转载 作者:太空宇宙 更新时间:2023-11-04 03:32:36 26 4
gpt4 key购买 nike

我正在尝试编写一个脚本来显示执行某些查询的时间我的脚本有两个问题:1. 为什么函数的结果是0?2. 如何让/copy 不会覆盖我的文件(test.txt)?

脚本:

#!/bin/bash

psql WYPOZYCZALNIA postgres<< EOF

CREATE OR REPLACE FUNCTION funkcja(i integer) returns double precision as'
DECLARE
czas_start double precision;
czas_stop double precision;
BEGIN
SELECT extract(epoch from now()) into czas_start;
insert into UZYTKOWNICY VALUES(16,''PIOTiR'',''510784543'');
SELECT extract(epoch from now()) into czas_stop;
RETURN czas_stop-czas_start;
end;
'language 'plpgsql';
\copy (select * from funkcja(50)) To 'test.txt'
\q
EOF

最佳答案

函数 NOW() 是 transaction_timestamp() 的别名,并且始终返回当前事务的开始时间,因此在存储过程中始终返回相同的值。请参阅here了解更多详情:

statement_timestamp() and transaction_timestamp() return the same value during the first command of a transaction,

要解决您的问题,请使用 timeofday()clock_timestamp() 而不是 NOW():

timeofday() is a historical PostgreSQL function. Like clock_timestamp(), it returns the actual current time, but as a formatted text string rather than a timestamp with time zone value.

要在 EXTRACT() 中使用它,请使用 timeofday()::TIMESTAMP 将结果转换为 TIMESTAMP:

SELECT extract(epoch from timeofday()::TIMESTAMP) into czas_start;
insert into UZYTKOWNICY VALUES(16,''PIOTiR'',''510784543'');
SELECT extract(epoch from timeofday()::TIMESTAMP) into czas_stop;

如何附加结果而不是覆盖输出文件

\copy 命令不支持追加而不是覆盖,因此最好不要使用 \copy,而是在 psql 中运行该函数并将输出重定向到文件:

#!/bin/bash

psql WYPOZYCZALNIA postgres<< EOF

CREATE OR REPLACE FUNCTION funkcja(i integer) returns double precision as \$BODY$
DECLARE
czas_start double precision;
czas_stop double precision;
BEGIN
SELECT extract(epoch from timeofday()::TIMESTAMP) into czas_start;
INSERT INTO UZYTKOWNICY VALUES(16,'PIOTiR','510784543');
SELECT extract(epoch from timeofday()::TIMESTAMP) into czas_stop;
RETURN czas_stop-czas_start;
end;
\$BODY$ language 'plpgsql';
EOF
psql WYPOZYCZALNIA postgres -t -A -c "SELECT funkcja(50)" >> 'test.txt'

psql 选项 -A 表示不对齐输出,-t 表示仅在输出中显示元组。

注意事项

  • 该函数接受一个参数,但不使用它。最终删除该参数。
  • 每次要运行该函数时都加载该函数是一个糟糕的设计。最好将函数定义与在两个不同文件中运行它分开。该函数应该仅通过数据库设置加载一次。

关于sql - postgreSQL中执行查询的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32680304/

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