PostgreSQL存储过程数据参数

时间:2011-05-13 18:50:00

标签: postgresql plpgsql

我有以下存储过程,它返回0结果,但如果单独运行查询,则会产生大量结果。我错过了什么。

CREATE OR REPLACE FUNCTION countStatistics(baselineDate Date) RETURNS int AS $$
DECLARE
    qty int;
BEGIN
    SELECT COUNT(*) INTO qty FROM statistics WHERE time_stamp = baselineDate;
    RETURN qty;
END;
$$ LANGUAGE plpgsql;

--Execute the function
SELECT countStatistics('2015-01-01 01:00:00') as qty;

返回0结果

SELECT COUNT(*) FROM statistics WHERE time_stamp = '2015-01-01 01:00:00';

返回100+结果

1 个答案:

答案 0 :(得分:7)

您将baselineDate参数声明为date

CREATE OR REPLACE FUNCTION countStatistics(baselineDate Date)

但将其用作timestamp

SELECT COUNT(*) INTO qty FROM statistics WHERE time_stamp = baselineDate;

您正在进行隐式转换,因此countStatistics('2015-01-01 01:00:00')将实际执行此SQL:

SELECT COUNT(*) INTO qty FROM statistics WHERE time_stamp = '2015-01-01';

并且,date被隐式转回timestamp之后,实际上会是这样:

SELECT COUNT(*) INTO qty FROM statistics WHERE time_stamp = '2015-01-01 00:00:00';

尝试更改您的函数声明以使用timestamp

CREATE OR REPLACE FUNCTION countStatistics(baselineDate timestamp)