gpt4 book ai didi

PostgreSQL 9.3 : Check only time from timestamp

转载 作者:行者123 更新时间:2023-11-29 12:11:55 26 4
gpt4 key购买 nike

我有下表,其中一个字段类型为 timestamp

Create table Test_Timestamp
(
ColumnA timestamp
);

现在插入一些记录进行演示:

INSERT INTO Test_Timestamp VALUES('1900-01-01 01:21:15'),
('1900-01-01 02:11:25'),
('1900-01-01 12:52:10'),
('1900-01-01 03:20:05');

现在我已经创建了带有两个参数的函数 Function_Test,即 St_timeEn_Time 这是varchar类型,其中我只传递时间,如00:00:01。在那个函数之后返回具有两次参数条件的表。

CREATE OR REPLACE FUNCTION Function_Test
(
St_Time varchar,
En_Time varchar
)

RETURNS TABLE
(
columX timestamp
)
AS

$BODY$

Declare
sql varchar;
wher varchar;

BEGIN

wher := 'Where columna BETWEEN '|| to_char(cast(St_Time as time),'''HH24:MI:SS''') ||' AND '|| to_char(cast(En_Time as time),'''HH24:MI:SS''') ||'';

RAISE INFO '%',wher;

sql := 'SELECT * FROM Test_Timestamp ' || wher ;

RAISE INFO '%',sql;

RETURN QUERY EXECUTE sql;

END;

$BODY$

LANGUAGE PLPGSQL;

---调用函数

SELECT * FROM Function_Test('00:00:00','23:59:59');

但是出现错误:

ERROR:  invalid input syntax for type timestamp: "00:00:01"
LINE 1: ...ELECT * FROM Test_Timestamp where ColumnA BETWEEN '00:00:01'...

最佳答案

您可以将列转换为时间:ColumnA::time

您还应该将时间(或日期或时间戳)作为 varchar 传递。而且你不需要为此使用动态 SQL 或 PL/pgSQL 函数:

CREATE OR REPLACE FUNCTION Function_Test(St_Time time, en_Time time)
RETURNS TABLE (columX timestamp)
AS
$BODY$
SELECT *
FROM Test_Timestamp
where columna::time between st_time and en_time;
$BODY$
LANGUAGE sql;

这样调用它:

select *
from Function_Test(time '03:00:00', time '21:10:42');

关于PostgreSQL 9.3 : Check only time from timestamp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29411595/

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