【发布时间】:2014-11-25 09:34:18
【问题描述】:
我正在尝试在 PostgreSQL 9.3.5 中实现一个以日期为参数的函数。
它应该涵盖以下所有条件并相应地返回结果。
select * from tablename
where sid is not null and dob >= '11-14-2014' order by dob;
-- Only Start Date
select * from tablename
where sid is not null and dob <= '11-21-2014' order by dob;
-- Only End Date
select * from tablename
where sid is not null and dob between '11-10-2014' and '11-21-2014' order by dob;
-- Both Start and End Dates are Given
select * from tablename
where sid is not null and dob is null;
-- Both Start and End Dates are Null
但是我上面的 SQL Fiddle 没有按预期工作。
我想要一个通用的实现,这样如果明天我有更多的new Date Fields 到条件搜索中,那么我可以将它们添加到where condition 中,但不能添加到IF 语句的每一行中。
【问题讨论】:
-
为什么需要单独的函数?您上述所有查询似乎都符合您的要求。一个单独的函数看起来有点太过分了,因为查询处理得很好并且更具可读性。
-
@DrColossos 我需要一个函数,因为我试图根据传递的参数(基于标准)获取详细信息,所以我想将它们变成一个函数,以便我可以使用该函数返回结果就像将它们用作单行查询时所做的那样。
标签: sql postgresql null date-range postgresql-9.3